2013-07-03 87 views
0

我相信我没有完全掌握jQuery中的变量范围,并且需要一些帮助来理解为什么变量“final_shasign”在AJAX内部表现良好,但在AJAX外部未定义,尽管它已被声明在AJAX之外。Javascript变量不通过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! 
+5

AJAX异步...的 –

+0

可能重复[如何返回从AJAX调用的响应?](http://stackoverflow.com/questions/14220321 /如何对返回的响应-从-AN-Ajax的呼叫) –

回答

1

AJAX是异步的,所以在一次尝试Ajax回调函数外部读取变量的值,它仍然undefined

所以编写你的逻辑在回调函数里面使用变量值,这里的回调函数是success

你也可以使用一个被攻击的对象。

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

3

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

AJAX is asynchronous因此,您的代码在AJAX语句之后将在响应有机会从“sha.php”返回之前运行。

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

$.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!而是任何JavaScript这是对AJAX响应依赖,应在success回调函数被调用。

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