说我有代码:

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返回“成功”,而new.php需要一个1来使testVar返回成功,如何为newVar获取“完成”?我猜想第二个发布请求会在第一个返回数据之前发生。

最佳答案

你可以做:

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

}

08-18 14:25
查看更多