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

How to send multiple post request with jquery?

本文关键字:请求 何使用 jquery      更新时间:2023-09-26

我需要在之前的post请求返回答案之前发送一个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
        });
}

现在假设我点击了按钮1,它将post请求发送到file1。当我在post1返回之前单击按钮2时,它会等待post1完成,然后发送请求。由于button1请求需要一些时间,我想在不等待post1结束的情况下发送post2请求。

我该怎么做?

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

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...);
}