开发者

Why won't IE recognize javascript code returned in AJAX call?

I have a (hopefully) simple question.

I'm using ajax to update a DIV on my current page. Within what's being inserted into the div is a script block that defines a variable. Within FF, I can access the variable, but IE doesn't see the var. Do I need to eval the returned code in some way for IE to recognize the variable?

As a simple example, if my ajax call returns this snippet of code and gets inserted into the div, I开发者_Python百科 get an alert in FF but not in IE:

<script language='JavaScript' type='text/JavaScript'> alert('Foo!'); </script>


Yes, the common workaround is to get all the script elements using getElementsByTagName() and then to eval() them.


You should return a JSON object as the result of the AJAX call and then use the json2.js Javascript stuff to evaluate it into a live object.

http://json.org/ has a link to JSON libraries for every language known to man, including Javascript.


The problem might be your JavaScript MIME type - you're using an unconventional type (type='text/JavaScript'):

<script language='JavaScript' type='text/JavaScript'> alert('Foo!'); </script>

You should try this instead:

<script type='text/javascript'> alert('Foo!'); </script>

I ran some tests recently and found that even modern browsers are pretty picky about this MIME type (skip to Additional Test #1), and will refuse to execute the JavaScript if it isn't set correctly: http://davidbcalhoun.com/2010/what-happens-when-we-serve-javascript-with-random-mime-types

If that's not the issue, try adding the script to the document Head:

document.getElementsByTagName('head')[0].appendChild(script);

This is what Google Analytics did until recently, so I would be surprised if it didn't work for you. You shouldn't need to use eval().

According to this page this page, IE is picky with nodes that haven't yet loaded, but the Head is almost guaranteed to have loaded, which is why it shouldn't have the same issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜