2017-06-28 45 views
-1

奇怪的錯誤分配全局變量,說:configundefined,但畢竟是假的:製作Chrome擴展程序,無法正常的JS文件(單個文件)

enter image description here

有沒有拼寫錯誤:

Image of Error

我不是JavaScript程序員,那是我的第一個擴展。我希望這是一個已知的問題。唯一使用的是AJAX。代碼如下所示:

var config; 
var req = new XMLHttpRequest(); 
req.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    config = JSON.parse(this.response); 
    } 
} 
req.open("GET", chrome.extension.getURL('/config.json'), true); 
req.send(); 
// here console.log(config) will return undefined. 

換句話說,變量分配很奇怪。

+0

還有一次,請提供*完整* [mcve]。在**絕對最低限度**時,您需要提供發生錯誤的線路。你的代碼中沒有任何地方試圖訪問'currency'屬性。因此,這是不完整的。一般來說,對於Chrome擴展程序調試問題,您幾乎總是需要提供* manifest.json *。 – Makyen

回答

1

由於XMLHTTPRequest是異步的(它們不會在代碼流動時立即發生),您必須將代碼放入其加載事件偵聽器中,或者調用一個函數,該函數將具有相同的代碼事件偵聽器:

var config; 
var req = new XMLHttpRequest(); 
req.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    config = JSON.parse(this.response); 

    // any code that uses config should be here 
    } 
} 

或:

var config; 
var req = new XMLHttpRequest(); 
req.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    config = JSON.parse(this.response); 

    // call doMagicStuff here 
    doMagicStuff(); 
    } 
} 

function doMagicStuff() { 

    // code that use config goes here 

} 
後者

,你可能也只是通過config作爲參數傳遞給doMagicStuff

相關問題