JavaScript while 循环回调

标签 javascript

function jQueryFunction(url,callback)
{ 
    $.ajax
    ({
        type: "GET",
        async: false,
        url: url,
        dataType: "jsonp",
        jsonp: "callback",
        jsonpCallback: "tpsHandler",
        success: function(json)
        {
            return callback(json);
        }
    });  
}

function tmpFunction(callback) 
{
    var jsonArray = new Array();
    var i = 0;

    while(true)
    {
        for(var j = 0; j < url_array.length; j++)
        {
            jQueryFunction(url_array[j], function(json){
                jsonArray[j] = json;
                i++;
            });
        }

        if(i >= url_array.length)
        {
            return callback(jsonArray);
        }
        else
        {
            alert(i);
        }
    }
}

当我调用 tmpFunction 时,网站一直向我显示“0”。为什么i总是0? tmpFunction 永远不会运行 for 循环吗?

最佳答案

来自 jQuery documentation :

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

如上所示,不能将 jsonp 与同步请求一起使用。所以是的,您的成功回调没有被执行(甚至不确定如果函数是同步的而不是仅返回值,jQuery 是否会触发回调)。

此外,我建议您永远不要发出同步 AJAX 请求,因为网络请求是长时间运行的操作,可能会破坏用户体验。相反,请采纳 @Altinak 的建议并使用 Deferred 对象。

关于JavaScript while 循环回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19170391/

相关文章:

javascript - 我如何以函数的形式编写这个脚本?

javascript - Facebook 页脚栏是一个 iframe,那么为什么它不与页面的其余部分一起重新加载呢?

javascript - 来自 DynamoDB Documentclient 的模拟 promise

javascript - 对非阻塞脚本的痴迷

javascript - 使用 Typescript 中的 Javascript 函数

javascript - 如何处理由 javascript 添加的元素的事件?没有 .on() jQuery?

javascript - 内联样式和 ReactCSSTransitionGroup

javascript - 如何使用 javascript 或 jQuery 动态更改 Bootstrap 5 下拉菜单的偏移量?

javascript - 带有 polyfilled Function.name 的 IE11 Javascript 行为

javascript - 如何删除事件监听器,以便在卸载组件时它不会尝试更新状态?