javascript - 如何获取 jsonpCallback 的同步结果?

标签 javascript jquery ajax asynchronous jsonp

我想在 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/

相关文章:

使用 openlayer 示例进行地理定位的 Javascript 代码

javascript - Jquery 更改 prev() 输入字段

Javascript 在页面加载时预选文本区域

javascript - DIV 如何在聊天脚本中滚动?

php - jQuery获取div内容并通过ajax发送到php脚本

javascript - JQGRID 中的自定义日期时间选择器

javascript - 有没有办法在页面加载时自动启动 css 转换或动画?

javascript - 用户提交表单后显示数据(从 API 调用检索)而不刷新页面

javascript - 如何对 JavaScript JQuery 函数中使用的变量进行串联

javascript:发送带有音频文件的 POST,然后重定向到新页面