[英]jQuery.ajax and XMLHttpRequest()?
I am trying to retrieve and execute the script contained in a file "example.js", using an AJAX request.我正在尝试使用 AJAX 请求检索并执行文件“example.js”中包含的脚本。
Let's say the example.js is:假设 example.js 是:
const greetings = {
hello: "Hello",
goodBye: "Good bye"
}
console.log(greetings.hello)
In another file, "get_script.js", I try to execute the code above using AJAX.在另一个文件“get_script.js”中,我尝试使用 AJAX 执行上面的代码。
The request and execution is working just perfect with jQuery:请求和执行与 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
while with a new XMLHttpRequest(), it doesn't:虽然使用新的 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
Notes:笔记:
Did I write something wrong in the second code?我在第二个代码中写错了吗? Can anybody explain the reason of this difference?任何人都可以解释这种差异的原因吗?
Thanks so much in advance!提前非常感谢!
The $.ajax call executed the script(like if it was in a <script>
tag) defining greetings
as a global constant and logging the value. $.ajax 调用执行脚本(就像它在<script>
标记中一样)将greetings
定义为全局常量并记录值。 The function you created in $.ajax success callback is never executed so is insignificant.您在 $.ajax 中创建的 function 成功回调永远不会执行,因此无关紧要。
The XHR call does not execute the js, but you do it manually with the fn
function. XHR 调用不执行 js,但您使用fn
function 手动执行。
The problem here is that the constant greetings
' scope is limited to the fn
function and not global.这里的问题是常量greetings
' scope 仅限于fn
function 而不是全局的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.