2017-07-19 67 views
0

如何使用ajax中的count變量?在ajax函數中,「count」顯示count,但是dessous什麼都沒有。使用變量out of ajax

var count; 
$.ajax({ 
cache : false, 
dataType: 'json', 
type : "POST", 
url  : "count.php", 
success : function(tdata){ 
count = tdata; 
console.log(count); //this works 

}    

}); 

console.log(count); //this doesn't work 
+0

你是什麼意思它不工作?它是否說「未定義」? – Bdloul

+1

您的ajax調用是異步的,所以您的控制檯日誌在響應之前得到打印,您可以使其同步,但這不是一個好習慣。 –

+3

可能的重複[如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

回答

1

$.ajax()是異步的,你需要等待它完成。

var count; 
$.ajax({ 
cache : false, 
dataType: 'json', 
type : "POST", 
url  : "count.php", 
success : function(tdata){ 
    count = tdata; 
    console.log(count); //this works 

}    

}) 
.done(() => { 
    // this code runs after ajax is resolved 
    console.log(count); 
}); 

參考http://api.jquery.com/jQuery.ajax/其他鏈接方法

+0

但我有大代碼!我可以不要.done(()=> {}); –

+0

代碼的大小並不重要。另外,根據你的環境,你可以嘗試使用async/await。 – Sean