- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 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/
这是我无法开始工作的 jquery 片段。我试图通过 jsonpCallback 调用 blackBackground() $(document).ready(function() { fun
更新1: 我刚刚从 jquery 1.4.4 升级到 1.6.1。这对原始问题中的脚本有何影响? 原始问题: 正如我测试的那样,我做了: $(document).ready(function() {
我想在 while 或 for 循环中调用 jsonpcallback 函数。但我得到了异步结果。如何在 jsonpcallback 中实现这一点。请任何人帮我解决这个问题或提供任何其他解决方案。 w
我在 URL 中使用不同的路径和查询对相同的 API 进行了不同的 Ajax 调用,但是使用相同的 jsonpCallback 我无法更改 当我调用一个 Ajax url - 一切正常! 但是当我需要
在向地理服务器发出请求时,我收到“parseResponse”不是一个函数。我尝试了几种方法来解决这个问题,但结果仍然是:“parseResponse不是一个函数” 我尝试在获取中设置同步选项,我尝试
我正在使用 Netflix 的 OData API 开发一个应用程序。我关注了Stephen Walther's blog entry关于如何查询 OData API。在其中,他使用了以下代码: $.
我在静态文件服务器 - GitHub Pages 上提供 JSONP JavaScript 文件。 这意味着我无法动态在服务器上设置 JSONP 回调函数名称... Dynamic example -
我是一名优秀的程序员,十分优秀!