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).

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Alex
  • 1,157
  • 3
  • 11
  • 25
  • 3
    Why do you need to use Ajax (as opposed to including the file using a ` – Pekka Jan 12 '12 at 21:20
  • http://stackoverflow.com/questions/3470895/small-ajax-javascript-library – Jerod Venema Jan 12 '12 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? – Pekka Jan 12 '12 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! – Alex Jan 12 '12 at 21:35

2 Answers2

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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • @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?](http://stackoverflow.com/q/197769) – Pekka Jan 12 '12 at 21:26
  • I have no particular reason to use AJAX over adding a – Alex Jan 12 '12 at 21:30
  • @Alex see my last comment underneath your question – Pekka Jan 12 '12 at 21:31
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);
Raynos
  • 166,823
  • 56
  • 351
  • 396