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

che*_*ker 6 ajax jquery json 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);
}
});
Run Code Online (Sandbox Code Playgroud)

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

Error: This method cannot be called until the open method has been called.
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢您的帮助!!!

che*_*ker 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();
                }
        });
Run Code Online (Sandbox Code Playgroud)

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

  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. 我用Google搜索并遇到了同样问题的网页,并提出了适用于我的解决方案.
  6. 官方jQuery票: