简体   繁体   中英

jQuery.ajax and XMLHttpRequest()?

I am trying to retrieve and execute the script contained in a file "example.js", using an AJAX request.

Let's say the example.js is:

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.

The request and execution is working just perfect with 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:

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:

  • in the XMLHttpRequest the function only execute if I store it in a variable and then call it.
  • I experienced that the async set to false is not the reason of this inequality.

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. The function you created in $.ajax success callback is never executed so is insignificant.

The XHR call does not execute the js, but you do it manually with the fn function.
The problem here is that the constant greetings ' scope is limited to the fn function and not global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM