Javascript 如何使用.js从另一个.js访问变量?

Javascript 如何使用.js从另一个.js访问变量?,javascript,Javascript,我想在一个js文件中使用一个属于另一个js文件的变量。 ie我想使用file2.js变量运行file1.js 有人知道怎么做吗? 是否可以从另一个.js文件访问变量 file1.js: oScript = document.createElement('script'); oScript.src = 'file2.js'; oScript.type = 'text/javascript'; document.body.appendChild(oScript); console.log(messa

我想在一个js文件中使用一个属于另一个js文件的变量。 ie我想使用file2.js变量运行file1.js

有人知道怎么做吗?
是否可以从另一个.js文件访问变量

file1.js:

oScript = document.createElement('script');
oScript.src = 'file2.js';
oScript.type = 'text/javascript';
document.body.appendChild(oScript);
console.log(message);
file2.js:

var message = [{"id":"01", "name":"Text A", "text":"more text"},{"id":"02", "name":"Text B", "text":"more text"}];

您需要确保
console.log(message)
在加载文件2之前不会运行。我建议使用AJAX,而不是尝试将文件注入HTML

var xhr = new XMLHttpRequest();
xhr.open('GET', 'file2.js');
xhr.onload = function() {
    eval(xhr.responseText);
    console.log(message);
    window.message = message; //Include this if you need message to be a global variable
};
xhr.send();

但是,我强烈建议使用JSON文件存储消息变量的值,并使用ajax加载该值,而不是使用JavaScript代码。

如果使用
load
事件,则只需
脚本
标记即可:

oScript = document.createElement('script');
oScript.src = 'file2.js';
oScript.type = 'text/javascript';
oScript.onload = function() {
    console.log(message);
};
document.body.appendChild(oScript);
或:


是否使用脚本标记调用这些文件?此代码应该可以正常工作<代码>消息看起来像一个全局变量,因此在插入脚本标记后,它应该是可读的。您遇到了什么问题?您可以创建可通过
窗口访问的全局变量。variableName
噢!非常感谢你。我能够用你的例子,使我的脚本工作。非常感谢你的解释。
oScript = document.createElement('script');
oScript.src = 'file2.js';
oScript.type = 'text/javascript';
oScript.addEventListener('load', function() {
    console.log(message);
});
document.body.appendChild(oScript);