jQuery Ajax内部循环仅在第一个循环上运行

时间:2018-11-21 06:18:36

标签: jquery ajax loops asynchronous

请帮助我理解为什么我的Ajax代码仅在第一个循环上运行。我有一个JSON数组。需要处理每个JSON,以从服务器获取响应。发生的情况是,“处理中...”作为数组JSON的长度登录到控制台的次数为0,然后第一个循环将运行ajax。之后,我收到超时错误。下面是我的代码。非常感谢!

        $.each(arrayJSON, function(i, arrayJSONInstance) {

            jsonString = JSON.stringify(arrayJSONInstance);

            $.ajax({
                url: "php/phpcode.php",
                data: {
                    data: jsonString
                },
                dataType: "json",
                type: "POST",
                timeout: 0,
                beforeSend: function (response) {
                    console.log("Processing...");
                },
                success: function (response) {
                    console.log(response);
                    console.log("Success!");
                },
                error: function(response) {
                    console.log("ERROR:\n");
                    console.log(response);
                }
            });
        });

1 个答案:

答案 0 :(得分:1)

我们知道,ajax调用是异步的,您的代码正在发送多个ajax调用(取决于数组的长度)。

尝试使用以下方式使ajax调用同步:

async: false

告诉我是否可以解决问题。