[英]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. 我正在使用ajax更新当前页面上的DIV。 Within what's being inserted into the div is a script block that defines a variable.
在div中插入的是定义变量的脚本块。 Within FF, I can access the variable, but IE doesn't see the var.
在FF中,我可以访问变量,但是IE看不到var。 Do I need to eval the returned code in some way for IE to recognize the variable?
我是否需要以某种方式评估返回的代码,以便IE识别变量?
As a simple example, if my ajax call returns this snippet of code and gets inserted into the div, I get an alert in FF but not in IE: 举一个简单的例子,如果我的ajax调用返回此代码段并插入到div中,则在FF中会收到警报,但在IE中不会:
<script language='JavaScript' type='text/JavaScript'> alert('Foo!'); <script language ='JavaScript'type ='text / JavaScript'> alert('Foo!'); </script>
</ SCRIPT>
是的,常见的解决方法是使用getElementsByTagName()
获取所有script
元素,然后对它们进行eval()
。
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. 作为AJAX调用的结果,您应该返回一个JSON对象,然后使用json2.js Javascript内容将其评估为活动对象。
http://json.org/ has a link to JSON libraries for every language known to man, including Javascript. http://json.org/包含指向人类已知的每种语言(包括Javascript)的JSON库的链接。
The problem might be your JavaScript MIME type - you're using an unconventional type (type='text/JavaScript'): 问题可能出在您的JavaScript MIME类型上-您使用的是非常规类型(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 我最近进行了一些测试,发现即使是现代浏览器也对这种MIME类型非常挑剔(跳至附加测试#1),如果设置不正确,则将拒绝执行JavaScript: http : //davidbcalhoun.com/ 2010 /乜发生-时,我们先得的JavaScript,与随机-MIME类型
If that's not the issue, try adding the script to the document Head: 如果这不是问题,请尝试将脚本添加到文档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. 这是Google Analytics(分析)直到最近才做的事情,所以如果它对您不起作用,我会感到惊讶。 You shouldn't need to use eval().
您不需要使用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. 根据此页面的本页 ,IE对尚未加载的节点很挑剔,但是几乎可以保证Head已加载,这就是为什么它不应该出现相同的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.