jQuery AJAX请求在IE8中失败并显示消息'错误:在调用open方法之前无法调用此方法。

时间:2010-12-29 20:20:54

标签: ajax json jquery xmlhttprequest ie-developer-tools

我正在使用jQuery 1.4.2并尝试执行简单的AJAX请求。目标URL返回一个JSON字符串(我用jslint验证它)。该请求适用于Firefox和Chrome,但不想在IE8中工作,我无法确定原因。这是电话:

jQuery.ajax({
url: 'http://' + domain + '/' + 'helper/echo/',
dataType: 'json',
success: function(data) {
 alert(data);
},
beforeSend: function(request, settings) {
 alert('Beginning ' + settings.dataType + ' request: ' + settings.url);
},
complete: function(request, status) {
 alert('Request complete: ' + status);
},
error: function(request, status, error) {
 alert(error);
}
});

IE将执行beforeSend回调和错误回调。错误回调警告消息:

Error: This method cannot be called until the open method has been called.

我的回复标头返回Content-Type: text/javascript; charset=UTF-8

IE正在发生什么事?我正在localhost上运行服务器,从http://localhost:8080/psxhttp://localhost:8080/helper发出请求。也许IE阻止了这个请求?我已经尝试安装Fiddler来分析请求流量,但它不会在我的机器上运行,因为它被锁定了。 Firebug让我,但一切似乎都很好。

感谢您的帮助!!!

1 个答案:

答案 0 :(得分:14)

好的,这是修复!请求使用window.XMLHttpRequest(),由于某种原因,它在IE8中无法正常工作。 jQuery没有失败回到window.ActiveXObject("Microsoft.XMLHTTP")

在AJAX调用之前将其添加到您的脚本中(仅在IE8中验证,而不是在其他IE中验证):

jQuery.ajaxSetup({
            xhr: function() {
                    //return new window.XMLHttpRequest();
                    try{
                        if(window.ActiveXObject)
                            return new window.ActiveXObject("Microsoft.XMLHTTP");
                    } catch(e) { }

                    return new window.XMLHttpRequest();
                }
        });

以下是我找到解决方案的方法:

  1. 如果问题是已修复的错误,请更新到jQuery 1.4.4。
  2. 逐步浏览Firebug调试器和DevTools调试器,直到结果看起来完全不同。
  3. 在第5899行,ajax()函数使用xhr()函数创建XmlHttpRequest对象。在Firefox中,它返回了良好的数据。在IE中,返回时所有字段都为Error: This method cannot be called until the open method has been called.
  4. 我在第5749行return new window.XMLHttpRequest();
  5. 分析了这个函数
  6. 我用Google搜索并遇到了同样问题的page,并提出了适合我的解决方案。
  7. Official jQuery ticket