首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery.ajax和XMLHttpRequest()?

jQuery.ajax和XMLHttpRequest()?
EN

Stack Overflow用户
提问于 2022-08-03 01:02:22
回答 1查看 134关注 0票数 0

我试图使用AJAX请求检索和执行包含在文件"example.js“中的脚本。

假设example.js是:

代码语言:javascript
复制
const greetings = {
    hello: "Hello",
    goodBye: "Good bye"
}
console.log(greetings.hello)

在另一个文件"get_script.js“中,我尝试使用AJAX执行上面的代码。

请求和执行非常适合于jQuery:

代码语言:javascript
复制
$.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(),但它没有:

代码语言:javascript
复制
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

备注:

  • 在XMLHttpRequest中,只有当我将其存储在变量中,然后调用它时,函数才会执行。
  • ,我体验到异步设置为false不是造成这种不平等的原因。

我在第二段代码中写错了什么吗?有谁能解释一下这种差异的原因吗?

提前谢谢你!

编辑04/08/2022

查看jQuery的函数,我发现它们自动执行检索到的代码的方法是将检索到的代码附加到脚本标记中作为文本,然后立即删除它。我在代码中这样做,并以$.get()的形式工作:

代码语言:javascript
复制
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引导我找到解决方案!

EN

回答 1

Stack Overflow用户

发布于 2022-08-03 01:52:30

$.ajax调用执行脚本(就像在<script>标记中那样),将greetings定义为全局常量并记录值。您在$.ajax成功回调中创建的函数从未执行过,因此是微不足道的。

XHR调用不执行js,但使用fn函数手动执行。

这里的问题是常数greetings的作用域仅限于fn函数,而不是全局的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73215279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档