2011-12-26 34 views
1

這裏是最初的代碼:jQuery的阿賈克斯獲得導致

var res = null; 
$.post('test.php', 'q=testdata', function(response) { 
    res = response; 
}); 

我需要在我的代碼,或Ajax調用後立即在某些時候使用res。我嘗試這樣做:

var res = null; 
$.post('test.php', 'q=testdata', function(response) { 
    res = response; 
    alert('Note 1: '+res); /* Returned exactly what I wanted */ 
}); 
alert('Note 2: '+res); /* Returned null. I need to use res here. How? */ 

怎麼可能使用res保持Ajax調用後所需的值?

回答

2

您的代碼發出異步Ajax請求,而第二警報同步執行。這意味着執行(順序)第二次警報時,響應可能不可用。

試着把它放在你的$.post後面:$.ajaxSetup({async:false})

它會強制警報以它們出現在代碼中的順序觸發。如果異步電話是您想要的,那麼我建議您遵循Sudhir的建議。

1

威爾東西這種幫助你:

 
var res = null; 
$.post('test.php', 'q=testdata', function(response) { 
    res = response; 
    doSomething(res); 
}); 

function doSomething(respo) { 
    //do someting with response 
}