JSONPでシンプルなサンプル

No Comments

JSONPでPHPとJavascriptでのシンプルなサンプルを見つけたので、メモ。

<pre>var php='action.php';
var mc=document.createElement('script');
mc.type='text/javascript';
mc.src=php+'?callback=when_get_data';
document.getElementsByTagName('head')[0].appendChild(mc);

function when_get_data(m){
	m=eval(m);
	var a;
	var b="";
	for(a in m){
		b+=a+":"+m[a]+"\n";
	}
	get_item("output").innerHTML=b;
}</pre>
<pre><?php
$dat=array('name'=>'John', birthday=>'19731129', 'time'=>date('Y/m/d H:i:s'));
$res='(' . json_encode($dat) . ')';
if($_GET['callback']){
	$res=$_GET['callback'] . '(\'' . $res . '\');';
}
header('Content-Type: text/javascript; charset=utf-8');
echo $res;
?></pre>

参考サイト
http://zapruder.main.jp/blog/?p=628

wordpressの更新情報をJSONPで出力する方法

No Comments

wordpressの更新情報をJSONPで出力できるらしい。
試してみたら、結構いい感じに出力された。まぁ、別の見せ方で更新情報を出力したいときに役に立ちそう。

dogmap.jpさんのところで解説されていた。

<?php
include_once('./wp-load.php');

// パラメータ取得
$limit = (int) (isset($_GET['limit']) && is_numeric($_GET['limit']) ? $_GET['limit'] : 5 );
$callback = wp_specialchars(attribute_escape(isset($_GET['callback']) ? $_GET['callback'] : 'callback'));
$charset = get_bloginfo('charset');

query_posts("showposts=$limit");		// 最終 $limit エントリ取得のループをつくる
if ( have_posts() ) {
	$out = null;

	// 最終 $limit エントリのタイトル・URL・日付を取得する
	while ( have_posts() ) {
		the_post();
		$out .= ( !empty($out) ? ',' : '');
		$out .= '{';
		$out .= '"title":"' . get_the_title() . '"';
		$out .= ',"link":"' . get_permalink() . '"';
		$out .= ',"pubdate":"' . the_date('Y-m-d H:i:s','','',false) . '"';
		$out .= '}';
	}

	// JSONP 形式で書き出す
	nocache_headers();
	header("Content-Type: application/x-javascript; charset=$charset");
	echo "$callback([$out]);";

} else {
	// 無ければ 404 Not Found を返す
	header("HTTP/1.0 404 Not Found");
	wp_die("404 Not Found");
}
?>

以上のソースコードを記述したファイルをwordpressのルートに配置する。

http://www.exsample.jp/get_archives.php?limit=5&callback=callback

にアクセスすると出力される。Javascriptで、callback関数を指定する。
これで出力されたJSONPを別のHTMLに出力される。

コミュニティサイトで使えると思う。JSON APIとして用意してもいいかもしれない。

参考サイト
WordPress の更新情報を JSONP 形式で出力