Javascript变量不会通过ajax更新

时间:2013-07-03 10:03:30

标签: javascript jquery ajax

我相信我还没有完全掌握jQuery中的变量范围,需要一些帮助来理解为什么变量“final_shasign”在AJAX中很好,但在AJAX之外是未定义的,尽管它是在AJAX之外声明的。

var final_shasign; // initial declaration outside of ajax block below

$.ajax({
    type: "POST",
    url: "sha.php",
    data: "amount="+amount+"&cn="+cn+"&currency="+currency+"&language="+language+"&orderid="+orderid+"&pspid="+pspid,
    success: function(response_data, final_shasign){
        var parsed_data = $.parseJSON(response_data);
        final_shasign = parsed_data.shasign;
        console.log ("inside nested ajax: " + final_shasign); //comes out fine
    }
});

console.log ("outside of nested ajax: " + final_shasign); //comes out as undefined!

3 个答案:

答案 0 :(得分:3)

这是因为在AJAX响应返回并更新变量值之前之前正在执行AJAX语句之外的console.log()

AJAX is asynchronous所以AJAX语句之后的代码将在响应有可能从“sha.php”返回之前运行。

如果您希望阻止请求异步执行,可以在async:false方法上设置$.ajax()

$.ajax({
    type: "POST",
    url: "sha.php",
    data: "amount="+amount+"&cn="+cn+"&currency="+currency+"&language="+language+"&orderid="+orderid+"&pspid="+pspid,
    async: false,
    success: function(response_data, final_shasign){
        var parsed_data = $.parseJSON(response_data);
        final_shasign = parsed_data.shasign;
        console.log ("inside nested ajax: " + final_shasign); //comes out fine
    }
});

But this isn't recommended!应该在success回调函数中调用任何依赖于AJAX响应的javascript。

var final_shasign;

$.ajax({
    type: "POST",
    url: "sha.php",
    data: "amount="+amount+"&cn="+cn+"&currency="+currency+"&language="+language+"&orderid="+orderid+"&pspid="+pspid,
    async: false,
    success: function(response_data, final_shasign){
        var parsed_data = $.parseJSON(response_data);
        final_shasign = parsed_data.shasign;
        console.log ("inside nested ajax: " + final_shasign); //comes out fine
        Func();
    }
});

function Func(){
   console.log ("outside of nested ajax: " + final_shasign);
}

答案 1 :(得分:1)

AJAX是异步的,所以当你尝试读取ajax回调函数之外的变量值时,它仍然是undefined

因此,在回调函数中使用变量值对您的逻辑进行编码,这里是success回调。

您也可以使用deferred对象。

请阅读:How do I return the response from an asynchronous call?

答案 2 :(得分:0)

你可以这样尝试

success: function(response_data, final_shasign){
    var parsed_data = $.parseJSON(response_data);
    final_shasign = parsed_data.shasign;

    passFinalvalue(final_shasign) 
    console.log ("inside nested ajax: " + final_shasign); //comes out fine
}

function passFinalvalue(getval)
{
 //do your stuff
}
相关问题