0

I want to load a Javascript file and execute it, using AJAX. I'm aware of solutions like jQuery's .getScript(), but I do not want to use any library! I'm also aware of writing <script> elements to the DOM, but as I said, I'm trying to achieve this with AJAX.

Here's a slimmed down version of my tries:

var http;
if(window.XMLHttpRequest){
    http=new XMLHttpRequest();
}
http.open('get','libs/teh-lib.js',false);
http.onreadystatechange=function(){
    if(http.readyState==4 && http.status==200){
        alert(http.responseText);
    }
}

Firebug shows the requests succeed, the right file is accessed, and a HTTP status 200 is shown. But the response seems to be empty. http.responseType and http.response seem to be empty, too. I also tried eval(http.responseText).

4
  • 3
    Why do you need to use Ajax (as opposed to including the file using a <script> tag)? Commented Jan 12, 2012 at 21:20
  • stackoverflow.com/questions/3470895/… Commented Jan 12, 2012 at 21:24
  • 1
    Ah, only now I realize what the problem is. Sorry. What you show should work (even though as said I don't think it's a good idea.) If you get an empty response, I'm pretty sure the problem is on server side. What happens if you access the URL directly in your browser? Commented Jan 12, 2012 at 21:27
  • @Pekka Oh you're right, the file I tried to load also shows empty when I access it directly in the browser... Looks like an underscore as first character of a file name doesn't work... Well thanks you made me find the problem! Commented Jan 12, 2012 at 21:35

2 Answers 2

1

but as I said, I'm trying to achieve this with AJAX.

Ajax is simply not the method for this - all it can do for you is fetch data, which you would then have to run through eval() to get them executed.

Creating a new script element in the DOM is really the natural way to go here.

Sign up to request clarification or add additional context in comments.

3 Comments

@j08691 it's the only way to do what the OP wants. I don't think it's a good idea. Re eval and evil...When is JavaScript's eval() not evil?
I have no particular reason to use AJAX over adding a <script> tag, it's just that I tried to do it with AJAX, and I don't manage to get it working!
@Alex see my last comment underneath your question
1
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function runScript() {
    eval(this.responseText);
});
xhr.open('get', 'script_url.js');
xhr.send();

As mentioned don't do this. Use <script>

var script = document.createElement("script");
script.src = 'script_url.js';
document.head.appendChild(script);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.