コールバックのイベントハンドリングを容易にする jQuery JSONP プラグイン
This adds a json() method to the $ function. The first argument is the URL to the JSON resource, with the text {callback} wherever the JSON callback method should be provided. In a JSONP URL, you would use jsonp={callback}; in a Yahoo! JSON URL you would use format=json&callback={callback}.
JSON for jQuery というプラグインを jQuery ライクな jQuery JSONP プラグインに書き換えてみました。
ダウンロード
jquery.jsonp.js (Uncompressed only) -- 2008-06-08
(function($) {
// $.jsonp
$.jsonp = {
};
// jsonp
$.fn.jsonp = function(url, fn) {
var self = this;
var key = 'fn' + (new Date()).getTime();
var script = $(document.createElement('script'))
.attr('type', 'text/javascript')
.attr('charset', 'UTF-8')
.attr('src', url.replace(/{fn}/, 'jQuery.jsonp.' + key));
$.jsonp[key] = function(json) {
setTimeout(function() {
script.remove();
}, 10);
self.each(fn, [json]);
};
jQuery('head', document)[0]
.appendChild(script[0]);
return self;
};
})(jQuery); // function($)
使い方
次のとおり、使い方は JSON for jQuery とほとんど変わりありません。JSON for jQuery は URL に埋め込むコールバック関数を {callback} で表しますが、このプラグインは {fn} としています。何でも短い名前が好みなんです。
var url = 'http://express.heartrails.com/api/json?jsonp={fn}';
var params = jQuery.param({
method: 'getStations',
x: 経度,
y: 緯度,
});
jQuery('#station')
.text('loading...')
.jsonp(url+'&'+params, function(json) {
//TODO:
});
仕組みや改善点など
JSON for jQuery のアイディアとと実装の枠組みは同じですが、いくつか改善しています。
script タグを生成するとき charset 属性を UTF-8 としています。また、コールバックしたタイミングで、生成した script 要素を削除するようにしています。このとき、IE がクラッシュしないように script 要素の削除を 10ms 遅らせて います。
コールバック関数をグローバルではなく $.jsonp オブジェクトに保持するようにし、 コールバックのコンテキストが jQuery オブジェクトの要素になるようにしています。
jQuery JSONP プラグイン は jQuery の振る舞いを理解する目的で作成したものですが、特定の場面でニーズがあるかもしれませんので公開します。ライセンスは jQuery と同じにしておきます。
関連情報
- fixedUI プラグイン
- jTemplates
- Cycle Plugin
- Flash Plugin
- tablesorter
- Interface Elements
-
- Interface Elements の Carousel とフォートラベル API で旅行写真の 3D ギャラリーを作る
- Interface Elements の Imagebox とフォートラベル API で旅行写真のギャラリーを作る
- Interface Elements の Slider で郵便番号を入力してみたが・・・
- Interface Elements の Slider で旅行写真を拡大(または縮小)表示する
- Interface Elements の Tooltips をいろいろな要素で使ってみた
- Interface Elements の Scrollto でページ内リンクをスムースにする
- Interface Elements の Carousel と YouTube Data API で動画のサムネイルを回転表示する
- Selectors
- Events
- DOM Manipulation
- AJAX
- Forms with Functions
- Using with Other Libraries
- Books
-
- Resources
