3

我一直在尝试让 ajax 调用在 IE9 中正常工作。我可以在网络数据中看到请求顺利通过。jQuery $.ajax() 调用返回的 jqXHR 对象包含响应数据。然而,我的成功/错误/完成回调没有触发。这是代码...

在我的脚本顶部:

// override xhr for browser that use XDR
if ('XDomainRequest' in window && window.XDomainRequest !== null) {

  // override default jQuery transport for IE
  jQuery.ajaxSettings.xhr = function() {
      try { return new XDomainRequest(); }
      catch(e) {
        console.log('test'); 
      }
  };

  // Maybe a 304 response is causing the callbacks not to fire?
  // This makes sure I'm getting 200
  jQuery.ajaxSettings.cache = false;

  // also, override the support check
  jQuery.support.cors = true;
}

然后我的ajax调用......很简单。

$.ajax({
    url: url,
    success: success,
    complete: complete,
    beforeSend: beforeSend,
    error: error
});

function success(response, textStatus, jqXHR){
    console.log('success');
    if( typeof fn == 'function'){
        fn(response.data);
    } else {
        console.log('Invalid callback supplied for dataGateway');
    }
}

function error(jqXHR, textStatus, errorThrown){
    console.log("Could not retrieve data from API.");
    return;
}

function complete(jqXHR, textStatus){
    console.log('complete');
}

// This is the only callback that gets fired
function beforeSend(jqXHR, settings){
    console.log('before send');
}

有谁知道如何解决这个问题?

4

2 回答 2

2

不知道这是否有帮助,但这是我的工作 ajax 调用的一个示例。

    $.ajax({
        url: "http://myurl.com",
        type: "POST",
        dataType: "xml",
        data: GetCurrentUserSoapEnv, //my variable containing the xml I sending
        complete: processResult, //the function to call on completion
        contentType: "text/xml; charset=\"utf-8\""
});
于 2012-06-28T22:37:45.573 回答
0

我知道这与您正在寻找的方法不同,并且您可能已经解决了您的问题,但我最近正在处理类似的 IE 兼容性问题,我认为仅使用 XDomainRequest 的内置处理程序会更简单。

尽管为拒绝遵循标准的浏览器设置例外是令人厌恶的,但我在我的项目中使用类似以下的内容来解释这种情况:

    // This is necessary due to IE<10 having no support for CORS.
function fallbackXDR(callObj) {
    if (window.XDomainRequest) { 
        var xdrObj = new XDomainRequest();
        xdrObj.timeout = callObj.timeout;
        xdrObj.onload = function() {
            success({data:xdrObj.responseText});
            complete();
        };
        xdrObj.onerror = function() {
            error(xdrObj);
        };
        xdrObj.ontimeout = function() {
            callObj.xdrAttempts = callObj.xdrAttempts++ || 1;
            if (callObj.xdrAttempts < callObj.maxAttempts) {
                fallbackXDR(callObj);
            }
        };
        xdrObj.onprogress = function() {
            // Unfortunately this has to be included or it will not work in some cases.
        };

        // Use something other than $.param() to format the url if not using jQuery.
        var callStr = callObj ? '?'+$.param(callObj.urlVars) : '';
        xdrObj.open("get", callObj.url+callStr);
        xdrObj.send();
    } else {
        handleError("No XDomainRequest available.", callObj);
    }
}//fallbackXDR()
于 2013-01-07T00:17:04.740 回答