我想在 while 或 for 循环中调用 jsonpcallback 函数。但我得到了异步结果。如何在 jsonpcallback 中实现这一点。请任何人帮我解决这个问题或提供任何其他解决方案。
window.onPublitoryOebPart = function(json) {
window.publitoryOebPartJson = json;
content = patchEditedContent(json);
saveOebPartToc(content);
}
i = 0;
while(i < $("#oeb_parts_count").val()) {
return unless $("#oeb-part-file-url-"+i).length > 0
fileUrl = $("#oeb-part-file-url-"+i).html();
$.ajax({
url: fileUrl,
crossDomain: true,
dataType: "script",
jsonpCallback: "onPublitoryOebPart"
})
i++;
}
最佳答案
JavaScript 无法获得“同步”JSONP结果。这是因为 JSONP 涉及创建一个新的脚本元素;这样动态创建的脚本元素只能异步加载资源。
就use the success
callback用于 JSONP 请求并异步处理响应。仅当服务不允许指定动态函数时,才需要/有用手动指定 jsonpCallback
。
如果在循环中使用 success
回调,则 read up on closures 也很重要(然后 read more )。
例如:
var i = 0; // Don't forget the "var"
while(i < $("#oeb_parts_count").val()) {
var elm = $("#oeb-part-file-url-"+i);
if (!elm.length) { return; } // Make sure to use valid syntax
var fileUrl = elm.html();
$.ajax({
url: fileUrl,
crossDomain: true,
dataType: "script",
success: function (i, fileUrl) {
// Return a closure, the i and fileUrl parameters above
// are different variables than the i in the loop outside.
return function (data) {
// Do callback stuff in here, you can use i, fileUrl, and data
// (See the links for why this works)
alert("i: " + i + " data: " + data);
};
})(i, fileUrl) // invocation "binds" the closure
});
i++;
}
通过命名函数创建闭包可能会更简洁,但概念都是相同的。
<小时/>同步 XHR 请求也是非常不鼓励的; XHR 不是 JSONP,尽管此类请求也是使用 jQuery.ajax 函数创建的。
关于javascript - 如何获取 jsonpCallback 的同步结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164578/