我试图使用AJAX请求检索和执行包含在文件"example.js“中的脚本。
假设example.js是:
const greetings = {
hello: "Hello",
goodBye: "Good bye"
}
console.log(greetings.hello)在另一个文件"get_script.js“中,我尝试使用AJAX执行上面的代码。
请求和执行非常适合于jQuery:
$.ajax({
method:"GET",
async: false,
url: "example.js",
success: function (response) {
new Function(response)
}
});
console.log(greetings.goodBye)
//output in the console:
// "hello" - from example.js
// "goodbye" - from get_script.js虽然使用了一个新的XMLHttpRequest(),但它没有:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status === 200) {
const fn = new Function(xhr.response)
fn();
}
}
xhr.open("GET" , "example.js" , false);
xhr.send();
console.log(greetings.goodBye)
// the file is retrieved without problems.
//output in the console:
// "hello" - still getting the console.log() from example.js!
// So the script is executed, right?
// Uncaught ReferenceError: greetings is not defined备注:
我在第二段代码中写错了什么吗?有谁能解释一下这种差异的原因吗?
提前谢谢你!
编辑04/08/2022
查看jQuery的函数,我发现它们自动执行检索到的代码的方法是将检索到的代码附加到脚本标记中作为文本,然后立即删除它。我在代码中这样做,并以$.get()的形式工作:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status === 200) {
const script = document.createElement("script")
script.text = xhr.response;
document.head
.appendChild(script)
.parentNode
.removeChild(script);
}
}
xhr.open("GET" , "example.js" , false);
xhr.send();
console.log(greetings.goodBye)
//output in the console:
// "hello" - from example.js
// "goodbye" - from get_script.js显然,jQuery就是这样做的。希望我没有犯任何错误。
感谢用户Musa引导我找到解决方案!
发布于 2022-08-03 01:52:30
$.ajax调用执行脚本(就像在<script>标记中那样),将greetings定义为全局常量并记录值。您在$.ajax成功回调中创建的函数从未执行过,因此是微不足道的。
XHR调用不执行js,但使用fn函数手动执行。
这里的问题是常数greetings的作用域仅限于fn函数,而不是全局的。
https://stackoverflow.com/questions/73215279
复制相似问题