views:

180

answers:

6

I'm having trouble getting the follow code to work in Internet Explorer, it doesn't seem to want to execute the code sent back from the server via Ajax, it just does nothing:

var ajax = new ActiveXObject('Microsoft.XMLHTTP');
ajax.open('GET','http://fromsitewebsite.com/javascript.js',true);
ajax.setRequestHeader('Connection','close');
ajax.onreadystatechange = function()
 {
   if ( ajax.readyState == 4 )
   {
    document.body.innerHTML += '<script type="text/javascript">'+ajax.responseText+'</script>';
   }
 };

ajax.send('');

I've tried doing this with still no luck;

  document.body.innerHTML += '<script type="text/javascript">('+ajax.responseText+')()</script>')

Cheers

A: 

Try to eval the returned code.

A: 

You might have to create the script node and then set its content via the "innerText" attribute instead of "innerHTML". That's kind-of a weird thing to do anyway. You could just add a script element and set its "src" attribute to the URL you're using in the AJAX call.

When you say it "just does nothing", have you checked for script errors?

Pointy
+1  A: 

Why don't you try:

var scriptElmnt  = document.createElement('SCRIPT');
scriptElmnt.type = 'text/javascript';
scriptElmnt.src  = '/javascript.js';
document.body.appendChild(scriptElmnt);

If I remember correctly, this works as expected

Jacco
A: 

In case of IE you need to use execScript method

if ( ajax.readyState == 4 )  
{  
    if (window.execScript)  
        window.execScript(ajax.responseText);  
    else  
        document.body.innerHTML += '<script type="text/javascript">'+ajax.responseText+'</  script>';  
}

eval, which is recommended above, has some specific in IE

Aquatic
+2  A: 

To get IE to handle the content of the script tag properly, you need to set the .text value.

var scrElem = document.createElement('script');
scrElem.type = 'text/javascript';
scrElem.text = ajax.responseText;
document.body.appendChild(scrElem);
scunliffe
Thanks for the solution, this works as expected
Gary Green
A: 

A few things.

First of all eval() is evil. If you use it in a heavy javascript driven application it will slow down it significantly.

Also, why load javascript code? A good idea is to think of an other approach. If it's a small script just have it loaded, the user will cache it and load times will be comfortable. If it's server values you want added to your page use AJAX and load JSON instead. If the javascript file is large try minify it and deliver it from the server using gzip. If non of the above, IE supports a attribute on the script called defer="defer" it will render and execute your new added code. But I wouldn't recommend it since it's only supported by IE.

..fredrik

fredrik