Skip to content

Instantly share code, notes, and snippets.

@kanetei
Last active August 24, 2017 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanetei/641ce783a5641a04d3d93a6c1e5dce93 to your computer and use it in GitHub Desktop.
Save kanetei/641ce783a5641a04d3d93a6c1e5dce93 to your computer and use it in GitHub Desktop.
【concrete5】特定のページタイプ(例:'news')の内容をJSONPで出力する
<?php
// application/controllers/api.php
namespace Application\Controller;
use PageList;
use Core;
use Page;
use URL;
class Api extends \Concrete\Core\Controller\Controller {
function pages()
{
$dh = Core::make('helper/date');
$nh = Core::make('helper/navigation');
$js = Core::make('helper/json');
$pl = new PageList();
$pl->filterByPageTypeHandle('news');
$pl->sortByPublicDateDescending();
$pages = $pl->get();
$array = array();
foreach ($pages as $page) {
$o = new \stdClass;
// $o->cID = $page->getCollectionID();
$date = $dh->formatDateTime($page->getCollectionDatePublic(), true);
$o->date = date('Y-m-d', strtotime($date));
$pubTime = strtotime($page->getCollectionDatePublic());
// 60 seconds, 60 minutes, 24 hours, 10 days
$o->new = ((time() - $pubTime) < (60 * 60 * 24 * 10)) ? true : false;
$o->title = $page->getCollectionName();
$pagelink = $page->getAttribute('news_pagelink');
$otherpage = $page->getAttribute('news_otherpage');
$exlink = $page->getAttribute('news_exlink');
if($pagelink) {
$url = '';
} else {
if(!empty($exlink)) {
$url = $exlink;
} elseif(!empty($otherpage)) {
$url = $nh->getCollectionURL(Page::getByID($otherpage));
} else {
$url = $nh->getCollectionURL($page);
}
}
$o->link = $url;
$array[] = $o;
}
// Core::make('helper/ajax')->sendResult($array);
if(isset($_GET['callback'])){
$callback = $_GET['callback'];
}
header('Content-Type: application/javascript');
$r = $js->encode($array);
echo $callback . '('. $r .')';
}
}
<?php
// application/bootstrap/app.php
Route::register('/api/pages.json','Application\Controller\Api::pages');
// JSONP取得例
$(function(){
$.getJSON('http://www.example.com/api/pages.json?callback=?')
.success(function(data){
for(var i in data){
html = '<dt>' + data[i].date;
if(data[i].new) {
html += '<span class="label-new">New!</span>';
}
html += '</dt>';
html += '<dd>';
if(data[i].link) {
html += '<a href="' + data[i].link + '" target="_blank">';
}
html += data[i].title;
if(data[i].link) {
html += '</a>';
}
html += '</dd>';
$(".notice-list").append(html);
}
})
.error(function(jqXHR, textStatus, errorThrown) {
console.log("error:" + textStatus);
console.log("text:" + jqXHR.responseText);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment