[JSONP-SE] JSONP Static Emulation

JSONP, JSON with Padding, is available not only with dynamic contents from server-side CGI etc., but also with static contents, just static files.

However, such static JSONP files do NOT allow to change Padding, name of callback function.
JSON with FIXED padding is a kind of JSONP? It's just a mere JavaScript file?
callback(
    { foo: 'HOGE', bar: 'POMU' } // JSON content
);
You may need to manage a queue when you handle multiple JSONP calls.

Now, the JSONP-SE is the solution for this.
JSON-SE means JSON Static Emulation.
Change the padding, "callback" in code above, to the six lines below:
( function (data) {
    var list = document.getElementsByTagName( 'script' );
    var temp = list[list.length-1].src.match( /[\?\&]callback=([A-Za-z0-9\_\.\[\]]*)/ );
    var func = temp ? temp[1] : 'callback';
    eval( func+"(data)" );
})(
    { foo: 'HOGE', bar: 'POMU' } // JSON content
);

This is still a static file, however, you could specify any callback function name you like.
The JSON content in JSON-SE is exactly the same as it in JSON.

You could load JSONP-SE file via <script> element in <body> element.
<script type="text/javascript" src="test.js?callback=hello"></script>
The callback function "hello" would be called.
<script type="text/javascript" src="test.js"></script>
Without ?callback=... argument is not specified, the default function "callback" would be called instead.

You could generate <script> element via DOM.
    var script = document.createElement( 'script' );
    script.charset = 'utf-8';
    script.type = 'text/javascript';
    script.src = 'test.js?callback=hello';
    document.lastChild.appendChild( script );
JSONP-SE must be loaded in the bottom of the dom tree.


Such trick, fetching argument from the src attribute of the script element loaded, is used in script.aculo.us as well.


* The original post of this was written in Japanese.