JSONP : FRONT-END STUDIO

来源:百度文库 编辑:神马文学网 时间:2024/04/29 18:47:32
再翻译一篇好了:remote json-jsonp
浏览器的安全机制使得XMLHttpRequest,iframe之类的控件不能进行跨域访问,从安全的角度讲,这也倒是无可厚非的事情,但是它的确限制了分布式web应用。
要解决跨域访问限制带来的问题,通常我们有3种策略:
本地服务器代理,flash,script标签
我这里提出一种新的非标准方法用script实现跨域访问:JSON with Padding, or simply JSONP
JSONP工作方式很简单,但是需要服务器的支持。首先要由客户端提交一段json格式的文本,然后你将其用小括号包起来,从而得到一个合法的js文档(也可能仅仅是一个js函数请求).
客户端将jsonp关键字加入到请求文本的前面。
很简单,通过一个空 的jsonp参数,返回的结果就是通过小括号包起来的json数据。
让我们看看del.icio.us JSON API 的例子:
例子中使用的script标签的src属性是这样的:
http://del.icio.us/feeds/json/bob/mochikit+interpreter
得到的结果:
if(typeof(Delicious) == ‘undefined’) Delicious = {};
Delicious.posts = [{
“u”: “http://mochikit.com/examples/interpreter/index.html”,
“d”: “Interpreter - JavaScript Interactive Interpreter”,
“t”: [
“mochikit”,”webdev”,”tool”,”tools”,
“javascript”,”interactive”,”interpreter”,”repl”
]
}]
按照JSONP,上面的请求在语义上等同于下面的URL:
http://del.icio.us/feeds/json/bob/mochikit+interpreter?jsonp=if(typeof(Delicious)%3D%3D%27undefined%27)Delicious%3D%7B%7D%3BDelicious.posts%3D
这个uRL本身没什么意思,不过如果我们想要知道什么时候文档可用的时候呢?下面用过例子来跟踪一下:
var delicious_callbacks = {};
function getDelicious(callback, url) {
var uid = (new Date()).getTime();
delicious_callbacks[uid] = function () {
delete delicious_callbacks[uid];
callback();
};
url += “?jsonp=” + encodeURIComponent(”delicious_callbacks[” + uid + “]”);
// add the script tag to the document, cross fingers
};
getDelicious(doSomething, “http://del.icio.us/feeds/json/bob/mochikit+interpreter”);
这个试验中的URL是类似这样的:
http://del.icio.us/feeds/json/bob/mochikit+interpreter?jsonp=delicious_callbacks%5B12345%5D
delicious_callbacks[12345]([{
“u”: “http://mochikit.com/examples/interpreter/index.html”,
“d”: “Interpreter - JavaScript Interactive Interpreter”,
“t”: [
“mochikit”,”webdev”,”tool”,”tools”,
“javascript”,”interactive”,”interpreter”,”repl”
]
}])
看看,因为我们使用了圆括号,所以JSONP请求能够传入到函数中。
ps:我在官方文档中看到的参数不是jsonp,而是callback,Yahoo !Map中用的也是callback