2016-03-19 126 views
1

說我有代碼:關於POST請求

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

Assumning test.php的返回「成功」和new.php需要AA 1的testvar返回成功,我怎麼得到一個「完整」的newVar ?我猜測第二個帖子請求會在第一個返回數據之前發生。

+3

把第二個帖子INSIDE回調的第一個帖子請求(所以旁邊testVar = 1) – Jeff

+0

我知道我可以做到這一點,但我想知道如果函數必須是這樣的,出於某種原因。 –

回答

1

你可以這樣做:

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

} 
+0

是的,我知道,這就是我解決它的方法。但是第二個帖子請求在回調之前被解僱了。這在瀏覽器中如何工作。它是否暫停了這部分功能並繼續。 –

0

如果第二請求參數取決於從第一來的結果,
然後確保你按順序發送請求,
意味着發送第二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的內容可以是單個值,數組或對象。
擁有成功和消息的價值觀,您可以輕鬆追蹤發生的情況,並在需要時提出通知。