Ajax 在IE 9下跨域访问
IE 9- XDomainRequest Domain Crossing Ajax Request.
I had a problem on Ajax call for some data from an azure service in one of my projects. it usually happens in the scenario like this: There is a page under one domain system. However, we need display the data from another domain system on this page. So it brings a problem of cross-domain. e.g. $.getJSON('another domain url', success callback function);
Issue
Generally, It can be solved by jQuery Aajx. However, JQuery JSONP may not work properly under IE 9- browser. That's the problem i need face with.
Solution
I research on many blogs and articles. There are two way to solve this problem: 1. Iframe: you can create an invisible iframe element and try to load the data as a text of iframe. Then you can get it by JS. however, if you have no right to get the support from background, it may not a good idea. 2. XDomainRequest: Microsoft provide a plugin called 'XDomainRequest' to support the cross-domain call under IE 9-. This is the solution i want to introduce.
This is a sample of the usage of XDomainRequest: var requester = new XDomainRequest(); requester.open('get', 'another domain request url'); requester.contentType = 'text/plain'; requester.onload = function (event) { //get data from requester.responseText console.log('success'); }; requester.onerror = function () { console.log('error'); }; requester.send();
However, it may not work in your code. Because you may put this piece of code in one of page events. that's a problem. because there is a limitation of the usage of XDomainRequest. IE 9- asks you to initialize the XDomainRequest under a global scope instead of one event handle. For example, The code is wrong like this:
$(function(){ var requester = new XDomainRequest(); requester.open('get', 'another domain request url'); requester.contentType = 'text/plain'; requester.onload = function (event) { //get data from requester.responseText console.log('success'); }; requester.onerror = function () { console.log('error'); }; requester.send(); });
The correct way should be like this: var requester = new XDomainRequest();
$(function(){ requester.open('get', 'another domain request url'); requester.contentType = 'text/plain'; requester.onload = function (event) { //get data from requester.responseText console.log('success'); }; requester.onerror = function () { console.log('error'); }; requester.send(); });
This is the point i want to tell you here. Thanks.