一些睡眠后如何从xmlhttp对象发送POST请求

时间:2012-10-14 09:23:10

标签: javascript

  

可能重复:
  How do I add a delay in a JavaScript loop?

我希望使用POSTxmlhttp对象发送一些javascript请求,而无需等待一些睡眠后的响应。在for循环内,正在发送此请求。如果我没有等待发送所有请求,我的浏览器暂时没有响应,也不允许从服务器端。如何在所有这些POST请求中安排睡眠? 这就是我正在使用的 -

for (var i = 0; i < users.length; i++) {
    var http = new XMLHttpRequest();
    //set args here, which is based elements of array users
    http.open('POST', '/user/home/index.php', true);
    //Set all headers here then send the request
    http.send(args);
}

1 个答案:

答案 0 :(得分:1)

没有办法延迟当前的脚本执行。您必须使用异步请求并重新构建代码。

所以如果你有这样的代码:

function postData() {
    for (var i = 0; i < users.length; i++) {
        var http = new XMLHttpRequest();
        //set args here, which is based elements of array users
        http.open('POST', '/user/home/index.php', true);
        //Set all headers here then send the request
        http.send(args);
        //access request result
        if (http.status == 200) {
            console.log(http.responseText);
        } else {
            console.log('request error');
        }
    }
}

像这样改变:

var userIndex = 0;

function postData() {
    if (userIndex >= users.length) {
        //no more users to process
        return;
    }

    var http = new XMLHttpRequest();
    //set args here, which is based elements of array users
    http.open('POST', '/user/home/index.php', true);

    //set request handler
    http.onreadystatechange = function() {
        if (http.readyState != 4) return;
        if (http.status == 200) {
            console.log(http.responseText);
        } else {
            console.log('request error');
        }
        //process next user index
        userIndex++;
        window.setTimeout(function() {
            postData(); //do it again
        }, 5000); //5 seconds delay
    };

    //Set all headers here then send the request
    http.send(args);
}

postData(); //start the request chain
相关问题