はてブのJSONPをJavaScriptで受け取るサンプル(alertしか知らない人向け)

仕事で使う(←どんなしごとだ)

リザルト

hbJsonp(
{
"count" : "65",
"url" : "http://blog.dtpwiki.jp/dtp/2006/10/tex_d999.html",
"bookmarks":
[
{
"timestamp": "2006/10/29 11:49:20",
"comment" : "",
"user" : "unineko",
"tags" :
[
"tex",
"\u5370\u5237"
]
},
{
"timestamp":"2006/10/14 18:09:10",
"comment" :"\u30b7\u30e7\u30c3\u30af\u3067\u304b\u3057\u3002\u3067\u3082\u3088\u304f\u8003\u3048\u308b\u3068ps\u3067\u3082pdf\u3067\u3082\u51e6\u7406\u7cfb\u4f9d\u5b58\u3068\u601d\u308f\u308c\u308b\u554f\u984c\u306b\u76f4\u9762\u3057\u305f\u3053\u3068\u304c\u3042\u3063\u305f\u306a\u3002\u3069\u3046\u3067\u3082\u3044\u3044\u3051\u3069\u30a2\u30b9\u30ad\u30fc\u304cTeX\u3063\u307d\u3044\u7d44\u7248\u30b7\u30b9\u30c6\u30e0\u4f5c\u3063\u3066\u306a\u304b\u3063\u305f\u3063\u3051\uff1f \u691c\u7d22\u3057\u305f\u3089EWB\u3063\u3066\u306e\u304c\u51fa\u3066\u304d\u305f\u3051\u3069\u2026\u3002",
"user" :"okgwa",
"tags" :[]
},
{
"timestamp":"2006/10/13 10:09:23",
"comment" :"",
"user" :"yugui",
"tags" :
[
"TeX"
]
},
...
],
"title" : "M.C.P.C.: TEX\u539f\u7a3f\u3092\u5370\u5237\u696d\u754c\u3067\u6301\u3066\u3042\u307e\u3057\u3066\u3044\u308b\u4ef6",
"eid" : "2954415",
"entry_url" : "http://b.hatena.ne.jp/entry/http://blog.dtpwiki.jp/dtp/2006/10/tex_d999.html",
"screenshot": "http://screenshot.hatena.ne.jp/images/120x90/6/b/8/b/c/3e3458b1bb910394878d4e11a80d98f4688.jpg"
}
)

※一部略

これって、HTMLのほうで、function hbJsonp(json) {} みたいなの用意しておくと、json は、上のいっぱい書いた値が入っている、ていうことでいいよね。

HTML

hbjsonp.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xml:lang="ja" lang="ja">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<title>HATENABOOKMARK
JSONP SAMPLE</title>
<meta http-equiv="content-script-type"
content="text/javascript" />
<meta http-equiv="content-style-type"
content="text/css" />
<script>
<!--
function startUp() { // hatena の
// JSONP を実行させるきっかけ
var script = document.createElement('script');
script.id
= 'http://b.hatena.ne.jp/entry/json/?url='
+ 'http://blog.dtpwiki.jp/dtp/2006/10/tex_d999.html'
+ '&callback=hbJsonp';
script.charset = 'UTF-8';
script.src = script.id;
document.lastChild.appendChild(script);
}
function hbJsonp(json) { // hatena の
// JSONPから呼ばれる
alert(json['count']+' User(s)');
// 65 User(s) ってでるよ。
alert('URL: '+json['url']);
var hbTags = json['bookmarks'][0]['tags'];
// [0]→1人目。全員分必要なら、User数でループ回そう!
alert('TAG: '+ hbTags.length + " items " );
for (var i = 0; i < hbTags.length; i++) {
alert('TAG[' + i + ']: '+ hbTags[i] );
}
}
-->
</script>
</head>
<body onload="startUp();">
<h1>HATENABOOKMARK JSONP SAMPLE</h1>
<p>説明:http://b.hatena.ne.jp/entry/json/
?url=http://blog.dtpwiki.jp/dtp/2006/10/tex_d999.html
&callback=hbJsonp から、JSONP を取得して
JavaScript で実行します。</p>
</body>
</html>

すべてalertで結果表示するのでわかりやすいと思います。

デコード忘れた

decodeURIほげほげいれてー