2012-05-17 24 views
0

我知道這已經被訪問了很多,我已經設法讓這個工作與其他項目。我繼承了這段在IE中不起作用的代碼塊:與IE的JS CORS問題 - 如何解決?

function loadTemplate(template, alt_cache_name) { 
    if (templates[template] !== undefined) { 
     if (alt_cache_name !== undefined) { 
      templates[alt_cache_name] = templates[template]; 
     } 
     return templates[template]; 
    } else { 

     return $.get(template, function (response) { 
      if (alt_cache_name !== undefined) { 
       templates[alt_cache_name] = response; 
      } 
      templates[template] = response; 
     }, 'text'); 
    } 
} 

問題出在$ .get()上。

template的值是特定html模板的網址。

我嘗試以下,但我不認爲返回類型是一樣的東西從$獲得()返回:

function createCORSRequest(method, url) { 
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr) { 
     xhr.open(method, url, true); 
    } else if (typeof XDomainRequest != "undefined") { 
     xhr = new XDomainRequest(); 
     xhr.open(method, url); 
    } else { 
     xhr = null; 
    } 
    return xhr; 
} 


function loadTemplate(template, alt_cache_name) { 
    if (templates[template] !== undefined) { 
     if (alt_cache_name !== undefined) { 
      templates[alt_cache_name] = templates[template]; 
     } 
     return templates[template]; 
    } else { 

     var request = createCORSRequest("GET", template); 
     var content = ""; 
     if (request) { 
      request.onload = function() { 
       //do something with request.responseText 
       console.log(request.responseText); 
       if (alt_cache_name !== undefined) { 
        templates[alt_cache_name] = response.responseText; 
       } 
       templates[template] = response.responseText; 
      }; 
     } 

     return request; 


     //   return $.get(template, function (response) { 
     //    if (alt_cache_name !== undefined) { 
     //     templates[alt_cache_name] = response; 
     //    } 
     //    templates[template] = response; 
     //   }, 'text'); 
    } 
} 

我甚至試過$.get有:

jQuery.support.cors = true; 

有人可以闡明如何讓這個工作?

回答

0

原來,jQuery插件here做到了。經進一步閱讀,this post也詳細解答。

- 更新 -

在進一步的測試似乎有一些問題與IE9和這個庫。任何其他人遇到任何問題?

0

我有一個類似的問題,我無法使用IE8/9上的CORS在運行時從CDN加載模板。我能得到它的工作由包括來自這裏的XHR XDR-adapter.js文件:

<!--[if lt IE 10]> 
<script src="xhr-xdr-adapter.js" type="text/javascript"></script> 
<![endif]--> 

的XHR XDR-適配器取代的XMLHttpRequest:https://github.com/intuit/xhr-xdr-adapter/blob/master/src/xhr-xdr-adapter.js

如下您可以將其包含在需要的地方具有不同的功能,它們在運行時計算出是否使用本機XMLHttpRequest或XDomainRequest。通過包含它,我可以使用jQuery和AngularJS來跨域加載模板。