这有点像打架的工作,但它会为您提供动态回调。基本上它依赖于file: 传输将非常快的事实。它设置了一个请求队列并一次发送一个。这是我能确定的唯一方法,以确保可以链接正确的响应和回调(以保证的顺序)。希望有人能想出更好的方法,但无法动态生成响应,这是我能做的最好的。
var JSONP = {
queue: [],
load: function(file, callback, scope) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = "text/javascript";
script.src = file;
head.appendChild(script);
},
request: function(file, callback, scope) {
this.queue.push(arguments);
if (this.queue.length == 1) {
this.next();
}
},
response: function(json) {
var requestArgs = this.queue.shift();
var file = requestArgs[0];
var callback = requestArgs[1];
var scope = requestArgs[2] || this;
callback.call(scope, json, file);
this.next();
},
next: function() {
if (this.queue.length) {
var nextArgs = this.queue[0];
this.load.apply(this, nextArgs);
}
}
};
这是我做的测试
window.onload = function() {
JSONP.request('data.js', function(json, file) { alert("1 " + json.message); });
JSONP.request('data.js', function(json, file) { alert("2 " + json.message); });
}
数据.js
JSONP.response({
message: 'hello'
});