ウェブサービスを作っています。

JSONP オブジェクトを作った

JSONP で、いちいちコールバック関数に名前つけて書くのが面倒なので、

var url = 'http://s.hatena.ne.jp/blog.json/http://d.hatena.ne.jp/hatenastar/?callback={callback}';
JSONP.request(url, function(json) {
    alert(json.star_count);
});

みたいに

JSONP.request(URL, コールバック関数);

だけで、JSONP できる JSONP オブジェクトを作りました。
URL のコールバック関数名部には {callback} と入れてください。
jQuery のソースとかを参考にして、一応ガベコレも実装してます。
jQuery ではすでにこんな感じのことができるので、単独で使う場合などにどうぞ。
既出だったら、ちょっと悲しい。


jsonp.js

var JSONP = {
    _jsc: (new Date).getTime(),
    request: function(url, callback) {
        var name = 'jsonp' + JSONP._jsc++;
        var script = document.createElement('script');

        window[name] = function(json) {
            callback(json);

            // GC
            window[name] = undefined;
            try { delete window[name]; } catch (e) {}
            document.getElementsByTagName('head')[0].removeChild(script);
        };

        script.type = 'text/javascript';
        script.src = url.replace(/\{callback\}/, name);
        document.getElementsByTagName('head')[0].appendChild(script);
    }
}