简体   繁体   English

jQuery内部有多个ajax调用,用于循环记录相同的响应

[英]jQuery multiple ajax calls inside for loop logging same responses

My code is something like this: 我的代码是这样的:

for (var i = 0; i < stf_file_names.length; i++) {
    var temp_file_name = stf_file_names[i];
    $.ajax({
        type: "POST",
        url: "php_scripts/some_script.php",
        data: {
            stf_file_name: temp_file_name
        },
        timeout: 600000,
        success: function (response) {
            console.log("SUCCESS : ", response);
            //pausecomp(2000);
        }
    });
}

Here, some_script.php updates a database in the backend and echo's the primary key of the updated row, which is a number. 在这里,some_script.php在后端更新数据库,并回显已更新行的主键,该键是一个数字。 But when I'm logging using the success function, I can see that it is logging only the primary key echoed by the last ajax call multiple times. 但是,当我使用成功函数进行日志记录时,我可以看到它仅记录了上次ajax调用多次回显的主键。

But if I use some kind of sleep function, which is pausecomp() in this case, it prints different the primary keys echoed. 但是,如果我使用某种睡眠功能(在这种情况下为pausecomp()),它将输出不同的主键回显。

I have looked at multiple stackoverflow questions regarding this and have not been to solve it. 我已经看过多个关于此的stackoverflow问题,但尚未解决。

async: false will do the job async: false将胜任

$.ajax({
        type: "POST",
        async: false,
        url: "php_scripts/some_script.php",
        data: 

However, this is not recommended, Better to make a loop by calling a function recursively from success. 但是,不建议这样做,最好通过从成功递归调用函数来进行循环。

Here is the example. 这是例子。

i=0;
function loop_stf_file_names(i){

    var temp_file_name = stf_file_names[i];
    $.ajax({
        type: "POST",
        url: "php_scripts/some_script.php",
        async: false,
        data: {
            stf_file_name: temp_file_name
        },
        timeout: 600000,
        success: function (response) {
            console.log("SUCCESS : ", response);
            if( i < stf_file_names.length ){
                loop_stf_file_names( ++i );
            }
        }
    });
}

$.ajax() is a async function. $.ajax()是一个异步函数。

By looping over ajax you are most probably sending the same data in all requests, due to which you are receiving same key for all requests. 通过遍历ajax,您很可能在所有请求中发送相同的数据,因此您将为所有请求接收相同的密钥。

Just sure , you send the next request when you have received the response from first request. 可以肯定,当您收到第一个请求的响应时,您将发送下一个请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM