2017-07-26 94 views
0

我在使用jquery $ .get獲取文本文件。我有以下代碼。jquery .get返回奇數結果

console.log("before the get"); 
$.get("testfile.txt", function(data){ 
    console.log("in the get"); 
    console.log(data); 
}); 
console.log("after the get"); 

在控制檯中,我希望看到

before the get 
in the get 
'...the data...' 
after the get 

相反,我得到

before the get 
after the get 
in the get 
'...the data...' 

爲什麼我收到的奇次?謝謝。

+0

'.get()'是異步的,所以它在處理過程中繼續執行,而腳本的其餘部分繼續執行 – j08691

+1

face palm - thanks much j08691 –

回答

2

這並不奇怪。這很正常,因爲get請求是異步的。獲得通話後的其他代碼不會等待獲得並繼續執行完成。

您必須在完成get調用後打印控制檯日誌消息。

console.log("before the get"); 
$.get("testfile.txt", function(data){ 
    console.log("in the get"); 
    console.log(data); 
    console.log("after the get"); 
}); 
-2

我更喜歡你讀這單證: aysnc:假

http://api.jquery.com/jquery.ajax/

它會告訴請求關閉異步

我希望這將有助於

所以,改爲使用$ .ajax() than $ .get()