2012-06-28 81 views
4

我一直在試圖讓AJAX調用在IE9中正常工作。我可以在網絡數據中看到請求順利通過。 jQuery $ .ajax()調用返回的jqXHR對象包含響應數據。然而,我的成功/錯誤/完整回調並不是解僱。下面的代碼...jQuery Ajax成功/錯誤回調沒有在IE中觸發

在我的腳本的頂部:

// 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'); 
} 

有沒有人知道如何解決這個問題?

回答

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\"" 
}); 
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()