HTML 5 before the standard due to the browser security issues do not allow direct cross-domain communication, so in order to achieve the purpose of cross-domain communication of various egg pain solution appeared, commonly used are: JSONP, using proxy files, address bar hash, etc., these methods appear in the resolution of cross-domain problems, It also increases the performance overhead and maintenance costs for front-end pages. The HTML5 new standard adds the "Cross-origin Resource sharing" feature, which enables cross-domain communication to be resolved only by configuring the HTTP protocol header.
Cross-origin Resource Sharing detailed explanation see:
Http://dvcs.w3.org/hg/cors/raw-file/tip/Overview.html
One of the most important cross-origin Resource sharing implementations is the configuration of the parameter "Access-control-allow-origin", which checks whether the cross-domain request can be passed through the secondary parameter.
such as: access-control-allow-origin:http://a.com to allow the domain name under a.com cross-domain access;
access-control-allow-origin:* means that all domain names are allowed cross-domain access.
If you need to read the read cookie:
Configuration parameters Required: Access-control-allow-credentials:true
Also set the parameter withcredentials to True when XHR initiates the request:
var xhr = new XMLHttpRequest ();
Xhr.open ();
Xhr.withcredentials = true; This is done behind Xhr.open, otherwise some versions of the browser will be abnormal, resulting in invalid settings.
Example code:
Php:
Header(' access-control-allow-origin:http://a.com ');Header(' Access-control-allow-methods:post,get ');Header(' Access-control-allow-credentials:true ');Echo ' Cross-domain Ajax '
Js:
var XHR = New XMLHttpRequest(); ;XHR.Open(' GET ', ' http://b.com/cros/ajax.php ', true);XHR.withcredentials = true;XHR.onload = function () { Alert(XHR.Response);//reposhtml;}; XHR.onerror = function () {Alert(' ERROR making the request. ');};XHR.Send(); |
Using the HTML5 cross-domain sharing feature to solve Ajax cross-domain data synchronization issues