1

我需要在之前发布请求返回答案之前发送一个发布请求。

这是一个例子。

<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 发送了 post 请求。当我在 post1 返回之前单击 button2 时,它等待完成 post1 完成然后发送它的请求。由于 button1 请求需要一些时间,我想发送 post2 请求而不等待 post1 结束。

我怎样才能做到这一点?

4

1 回答 1

-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...);
}
于 2013-07-05T13:37:33.187 回答