Reputation: 21
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:
Did I write something wrong in the second code? Can anybody explain the reason of this difference?
Thanks so much in advance!
EDIT 04/08/2022
Looking at the jQuery's functions I found out that their way to automatically execute the retrieved code is to append a script tag with the retrieved code as text and then immediately remove it. I did that in my code and worked just as $.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
Apparently this is how jQuery does it. Hope I didn't make any mistakes.
Thanks to user Musa for leading me to the solution!
Upvotes: 0
Views: 748
Reputation: 97672
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.
Upvotes: 1