如何用jquery发送多个帖子请求?

时间:2013-07-05 13:31:36

标签: php javascript jquery html post

我需要在之前的帖子请求返回答案之前发送帖子请求。

这是一个例子。

<button name="button1" onclick="post1();" >post1</button>
<button name="button2" onclick="post2();" >post1</button>

这是javascript代码

function post1(){
    $.post('file1.php', {req : "long process"}, function (data) {
           //do some stuff
        });
}
function post2(){
    $.post('file2.php', {req : "short process"}, function (data) {
           //do some stuff
        });
}

现在假设我点击了button1并将其发送请求发送到file1。当我在post1返回之前点击button2时,它等待完成post1完成然后发送它的请求。由于button1请求需要一些时间,我想发送post2请求而不等待post1结束。

我该怎么做?

1 个答案:

答案 0 :(得分:-2)

使用变量存储第一个帖子请求的状态。

var post1State = "not_sent";
var post2State = "not_sent";

function post1() {
    post1State = "pending_response";
    $.post('file1.php', {whatever}, function(data) {
        post1State = "received";

        /* Check if the second request has been
           queued; if yes, then send it off */
        if ("queued" == post2State) {
            triggerPost2();
        }
    });
}

function post2() {
    /* Don't send the second post if the first
       request is not complete; Also flag the
       second request as pending for later */
    if ("received" != post1State) {
        post2State = "queued";

        return;
    }

    triggerPost2();
}

function triggerPost2() {
    post2State = "pending_response"; // Mark second request as pending response

    $.post(whatever for post 2...);
}