이것은 일종의 일종의 일이지만 동적 콜백을 갖습니다. 기본적으로 그것은 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);
}
}
}}; // URL, 보안상의 이유로이 내가
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); });
}
Data.js
JSONP.response({
message: 'hello'
});
브라우저 요구 사항이 있습니까? – Hemlock
가능한 한 많은 브라우저에서 작동해야합니다. – erikvold
CORS를 사용하면'file :'호스트를 요청하여'Access-Control-Allow-Origin' 헤더를 반환 할 수 없기 때문에 결코 작동하지 않을 것입니다. – inf3rno