2017-06-28 48 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

相关问题