Gary Green
Gary Green

Reputation: 22395

Ajax: injecting code into Internet Explorer

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

Upvotes: 1

Views: 583

Answers (6)

fredrik
fredrik

Reputation: 17617

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

Upvotes: 0

scunliffe
scunliffe

Reputation: 63580

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

Upvotes: 2

Aquatic
Aquatic

Reputation: 5144

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

Upvotes: 0

Jacco
Jacco

Reputation: 23759

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

Upvotes: 1

Pointy
Pointy

Reputation: 413712

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?

Upvotes: 0

lutz
lutz

Reputation:

Try to eval the returned code.

Upvotes: 0

Related Questions