Jquery $ .ajax가 도메인 간 호출에서 IE에서 실패합니다.
.NET을 사용하여 도메인 간 요청을 수행하고 $.ajax있습니다. Firefox 및 Chrome에서 작동하지만 IE 7 또는 8에서는 호출하지 않습니다. 누구든지 다음과 관련된 문제를 말해 줄 수 있습니까?
- JSON 및 JSONP를 사용했습니다 (사용자 지정 제한으로 인해 사용을 중단했습니다).
Allow-access-control-origin내 사이트에서 이미 헤더를 사용하고 있습니다. (그렇지 않으면 Chrome과 Firefox는 성공적인 요청을하지 못했습니다.)- 이미 https://developer.mozilla.org/en/http_access_control을 시도했습니다.
암호:
$.ajax({
type: 'GET',
url: "http://anotherdomain.com/Service/GetControl?id=" + zoneID,
cache: false,
contentType: "application/x-www-form-urlencoded",
async: false,
beforeSend: function (request) {
//alert('before send');
//request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//request.setRequestHeader("X-PINGOTHER", "pingpong");
} ,
success: function (data, status) {
//alert("Data returned :" + data);
//alert("Status :" + status);
if (status == "success" && data != "")
$("#" + div.id).append(data);
else
$("#" + div.id).attr("style", "display:none;");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
여러 사이트에있는 다양한 팁을 시도했지만 아직 운이 없습니다.
IE의 문제가 도메인 간 요청을 허용하기 위해 보안 영역을 정의하지 않는 것에 의존하는지 확인할 수 있습니까? 설명은이 Microsoft 페이지 를 참조하십시오 .
OTOH, 이 페이지 에서는 IE7 및 이전 버전 이 도메인 간 호출을 수행 할 수 없다고 언급하지만 IE8은 JQuery가 사용하는 XMLHttpRequest와 다른 객체를 사용하여 할 수 있습니다. XDomainRequest가 작동하는지 확인할 수 있습니까?
수정 (2013-08-22)
두 번째 링크는 죽었으므로 여기에 웨이 백 머신 에서 가져온 정보 중 일부를 작성 합니다 .
지원되는 XDomainRequest : IE8
IE 팀은 XMLHttpRequest의 CORS 버전을 구현하는 대신 XDomainRequest라는 고유 한 개체를 사용했습니다. XDomainRequest의 사용은 더 많은 이벤트가 발생하여 XMLHttpRequest에서 단순화되었습니다 (온로드가 가장 중요 할 수 있음).
이 구현에는 몇 가지 제한 사항이 있습니다. 예를 들어,이 개체를 사용할 때 쿠키가 전송되지 않으므로 서버 측의 쿠키 기반 세션에서 골칫거리가 될 수 있습니다. 또한 ContentType을 설정할 수 없으므로 ASP.NET 및 기타 서버 측 언어에서 문제가 발생할 수 있습니다 ( http://www.actionmonitor.co.uk/NewsItem.aspx?id=5 참조 ).
var xdr = new XDomainRequest(); xdr.onload = function() { alert("READY"); }; xdr.open("GET", "script.html"); xdr.send();
IE8 및 IE9의 경우 XDR (XDomainRequest)을 사용해야합니다. 아래를 보면 $ .ajax와 유사한 형식으로되어있는 것을 볼 수 있습니다. 내 연구에 따르면 IE6 및 7 에서이 교차 도메인이 작동하도록 할 수 없습니다 (여전히 해결 방법을 찾고 있습니다). XDR은 IE8에서 처음 나왔습니다 (IE9에도 있음). 그래서 기본적으로 먼저 6/7을 테스트하고 AJAX를 사용하지 않습니다.
IE10 +는 다른 모든 브라우저와 마찬가지로 교차 도메인을 정상적으로 수행 할 수 있습니다 (Microsoft 축하합니다 ... 한숨).
그 후 'XDomainRequest in window (브라우저 스니핑보다 낫다)'를 테스트하고 JSON AJAX 요청을 그런 식으로 수행하는 경우, 그렇지 않으면 ELSE는 $ .ajax로 정상적으로 수행합니다.
도움이 되었기를 바랍니다!! 이 모든 것을 원래 파악하기 위해 나를 영원히 데려갔습니다.
// call with your url (with parameters)
// 2nd param is your callback function (which will be passed the json DATA back)
crossDomainAjax('http://www.somecrossdomaincall.com/?blah=123', function (data) {
// success logic
});
function crossDomainAjax (url, successCallback) {
// IE8 & 9 only Cross domain JSON GET request
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(); // Use Microsoft XDR
xdr.open('get', url);
xdr.onload = function () {
var dom = new ActiveXObject('Microsoft.XMLDOM'),
JSON = $.parseJSON(xdr.responseText);
dom.async = false;
if (JSON == null || typeof (JSON) == 'undefined') {
JSON = $.parseJSON(data.firstChild.textContent);
}
successCallback(JSON); // internal function
};
xdr.onerror = function() {
_result = false;
};
xdr.send();
}
// IE7 and lower can't do cross domain
else if (navigator.userAgent.indexOf('MSIE') != -1 &&
parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {
return false;
}
// Do normal jQuery AJAX for everything else
else {
$.ajax({
url: url,
cache: false,
dataType: 'json',
type: 'GET',
async: false, // must be set to false
success: function (data, success) {
successCallback(data);
}
});
}
}
Jquery는 이것을 설정하는 것뿐입니다. $.support.cors = true;그러면 교차 도메인 요청이 jquery 사용자의 모든 브라우저에서 제대로 작동합니다.
이 jQuery 플러그인을 설치하기 만하면됩니다 : jQuery Cross-Domain AJAX for IE8
이 1.4kb 플러그인은 Internet Explorer 8 및 9 에서 즉시 작동합니다 .
jQuery 뒤에 플러그인을 포함하고 정상적으로 ajax 요청을 호출하십시오. 다른 것은 필요하지 않습니다.
IE 용 jquery에 추가 전송을 추가합니다. (이 코드를 마지막에 스크립트에 추가하십시오)
$.ajaxTransport("+*", function( options, originalOptions, jqXHR ) {
if(jQuery.browser.msie && window.XDomainRequest) {
var xdr;
return {
send: function( headers, completeCallback ) {
// Use Microsoft XDR
xdr = new XDomainRequest();
xdr.open("get", options.url);
xdr.onload = function() {
if(this.contentType.match(/\/xml/)){
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(this.responseText);
completeCallback(200, "success", [dom]);
}else{
completeCallback(200, "success", [this.responseText]);
}
};
xdr.ontimeout = function(){
completeCallback(408, "error", ["The request timed out."]);
};
xdr.onerror = function(){
completeCallback(404, "error", ["The requested resource could not be found."]);
};
xdr.send();
},
abort: function() {
if(xdr)xdr.abort();
}
};
}
});
이것은 교차 도메인 AJAX 요청에 실패한 Jquery $ .ajax 문제를 해결했습니다.
건배.
여기에 오는 다른 사람들 은 XDomainRequest의 한계에 대해 이야기하는 http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx 를 읽는 것이 좋습니다.
jQuery 2.0을 사용하여 여전히이 문제가있는 사람을 위해 (저는 알고 있습니다) Jay Dave가 최고의 jQuery 해결 방법을 작성했지만 여전히 코드에 추가 할 몇 가지 사항이 있습니다.
- 요청에 대해 동일한 프로토콜 (HTTP-> HTTP 또는 HTTPS-> HTTPS)을 사용하고 있는지 확인하십시오. Ayush Gupta는 문제를 알 수있는 링크를 제공했습니다.
- no-op 함수를 사용하여 "진행 중"이벤트를 처리합니다 (이렇게하면 IE가 서버에서 첫 번째 비트를 수신 한 후 요청을 중단하는 것을 방지 할 수 있습니다.
전체 코드는 다음과 같습니다.
// add ajax transport method for cross domain requests when using IE9
if('XDomainRequest' in window && window.XDomainRequest !== null) {
$.ajaxTransport("+*", function( options, originalOptions, jqXHR ) {
// verify if we need to do a cross domain request
// if not return so we don't break same domain requests
if (typeof options.crossDomain === 'undefined' || !options.crossDomain) {
return;
}
var xdr;
return {
send: function( headers, completeCallback ) {
// Use Microsoft XDR
xdr = new XDomainRequest();
xdr.open("get", options.url); // NOTE: make sure protocols are the same otherwise this will fail silently
xdr.onload = function() {
if(this.contentType.match(/\/xml/)){
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(this.responseText);
completeCallback(200, "success", [dom]);
} else {
completeCallback(200, "success", [this.responseText]);
}
};
xdr.onprogress = function() {};
xdr.ontimeout = function(){
completeCallback(408, "error", ["The request timed out."]);
};
xdr.onerror = function(){
completeCallback(404, "error", ["The requested resource could not be found."]);
};
xdr.send();
},
abort: function() {
if(xdr) xdr.abort();
}
};
});
}
참고, 추가
$.support.cors = true;
was sufficient to force $.ajax calls to work on IE8
Simply add "?callback=?" (or "&callback=?") to your url:
$.getJSON({
url:myUrl + "?callback=?",
data: myData,
success: function(data){
/*My function stuff*/
}
});
When doing the calls (with everything else set properly for cross-domain, as above) this will trigger the proper JSONP formatting.
More in-depth explanation can be found in the answer here.
@Furqan Could you please let me know whether you tested this with HTTP POST method,
Since I am also working on the same kind of situation, but I am not able to POST the data to different domain.
But after reading this it was quite simple...only thing is you have to forget about OLD browsers. I am giving code to send with POST method from same above URL for quick reference
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;
}
var request = createCORSRequest("POST", "http://www.sanshark.com/");
var content = "name=sandesh&lastname=daddi";
if (request){
request.onload = function(){
//do something with request.responseText
alert(request.responseText);
};
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", content.length);
request.send(content);
}
Microsoft always ploughs a self-defeating (at least in IE) furrow:
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
CORS works with XDomainRequest in IE8. But IE 8 does not support Preflighted or Credentialed Requests while Firefox 3.5+, Safari 4+, and Chrome all support such requests.
I have the same problem in IE, I solved it by replacing:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
To
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
So basically upgrade your jquery version.
I had a similar problem in IE9 where some CORS calls were aborting, while others weren't. My app is also dependent on a promise interface, so the XDomainRequest suggestions above weren't EXACTLY what I needed, so I added a deferred into my service.get workaround for IE9. Hopefully it can be useful to someone else running across this problem. :
get: function (url) {
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var deferred = $.Deferred();
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onload = function() {
json = xdr.responseText;
parsed_json = $.parseJSON(json);
deferred.resolve(parsed_json);
}
xdr.send();
return deferred;
} else {
return $.ajax({
url: url,
type: 'GET',
dataType: 'json',
crossDomain: true
});
}
}
It's hard to tell due to the lack of formatting in the question, but I think I see two issues with the ajax call.
1) the application/x-www-form-urlencoded for contentType should be in quotes
2) There should be a comma separating the contentType and async parameters.
참고URL : https://stackoverflow.com/questions/3362474/jquery-ajax-fails-in-ie-on-cross-domain-calls
'IT TIP' 카테고리의 다른 글
| RSA를 통해 고유 한 공개 및 개인 키를 생성하는 방법 (0) | 2020.11.19 |
|---|---|
| 대다 관계에서 NSPredicate 대소 문자를 구분하지 않는 일치 (0) | 2020.11.19 |
| Tkinter :“Python이 Tk 용으로 구성되지 않았을 수 있습니다.” (0) | 2020.11.19 |
| numpy를 사용하여 Python에서 TIFF (가져 오기, 내보내기) 작업 (0) | 2020.11.19 |
| 전환 후 제약 조건을 적용하는 iOS 8 UIPageViewController (0) | 2020.11.19 |