Enable Cors to implement Ajax Cross-domain requests
One day of the month, you need to implement a requirement to send a request to another site with Ajax in the current site,b.com -> S.com, just start to think that nothing, not just a request, immediately wrote out, the result of a 200 of the request, there is a hint of information;
20141020162144
What is the situation, so find the Niang asked up, The approximate results are as follows (some of the text is directly taken over):
Cross-domain is a problem I often ask in a daily interview, and the word is not low in the front end, mainly because of security restrictions (homology policy, where JavaScript or cookies can only access content under the same domain)
Principle of Cors:
Cors defines a mechanism for cross-domain access, allowing Ajax to implement Cross-domain access. CORS allows network applications on one domain to submit Cross-domain AJAX requests to another domain. This is a simple function to send a response header to the server.
Suppose our page or application is already on the http://qq.111cn.net, and we intend to extract the data from the http://qq.111cn.net request. In general, if we use AJAX directly to request will fail, the browser will also return the "Source mismatch" error, "Cross-domain" is the origin.
Use Cors,http://qq.111cn.net to add only one header, you can allow requests from http://www.b.com, the following figure is my hander () setting in PHP, the "*" sign allows any domain to submit requests to our server:
Header ("access-control-allow-origin:*"); The
can also set a specified domain name, such as a domain name http://www.111cn.net, so that requests from this domain name are allowed:
Header ("access-control-allow-origin:http://www.111cn.net");
The header you are currently setting is "*", when any one of the requests comes in and we can process & respond to it, you can see the header information setting in the Debug tool, where a message in the red box is " Access-control-allow-origin:* ", indicating that we have enabled cors, as shown below.
Compatible with IE8 JavaScript
Does the browser support cors through XHR, merging <strong>xdomainrequest </strong> object presence to support all browsers
| The code is as follows |
Copy Code |
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 ("Get", "http://www.111cn.net"); if (request) { Datas.onload = function () { Data returned in do something with Request.responsetext,responsetext server }; Request.send (); } |