簡體   English   中英

關於發帖請求

[英]Regarding post requests

說我有代碼:

var testVar = 0;
var newVar = "";

function(){
    var info = "hello";
    $.post("test.php", {"info":info}, function(data){
        if(data == "success"){
             testVar = 1;
        }
        else{
             testVar = 0;
        }
    });
    $.post("new.php", {"testVar":testVar}, function(data2){
        if(data2 == "success"){
            newVar = "Complete";
        }
        else{
            newVar = "Failed";
        }
    });
}

假設 test.php 返回“success”並且 new.php 需要 aa 1 才能讓 testVar 返回成功,我如何獲得 newVar 的“Complete”? 我猜第二個 post 請求會在第一個返回數據之前發生。

你可以做:

var testVar = 0;
var newVar = "";

var secondFunction = function(){
     $.post("new.php", {"testVar":testVar}, function(data2){
        if(data2 == "success"){
            newVar = "Complete";
        }
        else{
            newVar = "Failed";
        }
    });
};
function(){
    var info = "hello";
    $.post("test.php", {"info":info}, function(data){
        if(data == "success"){
             testVar = 1;
        }
        else{
             testVar = 0;
        }
        secondFunction();
    });

}

如果第二個請求的參數取決於第一個請求的結果,
然后確保按順序發送請求,
意思是只有在您收到第一個post的回復后才發送第二個post

此外,您應該准備好您的響應,以包含成功標志和有效負載標志。

操作成功

{success : "true", message : "operation successful", value : "1"}

手術失敗

{success : "false", message : "operation failed", value : "0"}

考慮下面的例子

function(){

    var info = "hello";

    $.post("test.php", {"info":info}, function(data){

        if (data.success != false){

            $.post("new.php", {"testVar":data.value}, function(data){
                if (data.success != false){
                    console.log(data.message) // this is the success message from the second request
                    // process the data from the second response,
                    // var = data.value ...
                }
                else{
                    console.log(data.message) // handle the failed state for the second request
                }
            },"json");

        }
        else{
            console.log(data.message)
        }

    },"json");

}

只有在第一個請求成功時才會觸發第二個請求。
您的響應具有一定的一致性, value的內容可以是單個值、數組或對象。
擁有成功的價值和消息,您可以輕松跟蹤發生的事情,並在需要時調出通知。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM