Cross-domain communication

We generally use ajax for front-end and back-end interactions, which is our commonly used XHRHttpRequest object. Does this support cross-domain communication?

Let's take a look next (IE5,6 we ignore xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); )

In standard browsers, the XMLHttpRequest object is already an upgraded version, which supports more features and can be cross-domain.
However, if you want to implement cross-domain requests, you need the relevant cooperation of the backend.

The background needs to set the header to allow cross-domain header('Access-Control-Allow-Origin:http://www.a.com'); //This is the domain that allows access to the resource

 1 var xhr = new XMLHttpRequest();
 2         xhr.onreadystatechange = function() {
 3             if (xhr.readyState == 4) {
 4                 if (xhr.status == 200) {
 5                     alert(xhr.responseText);
 6                 }
 7             }
 8         }
 9         xhr.open('get', 'elseDomain_url', true);
10         xhr.send();

 

XMLHttpRequest : Adds a lot of functions. It is not recommended to use the onreadystatechange event to monitor. It is recommended to use onload

XDomainRequest : If IE wants to implement cross-domain requests, use the XDomainRequest object in IE, as follows

1 var oXDomainRequest = new XDomainRequest();
2         oXDomainRequest.onload = function() {
3             alert(this.responseText);
4         }
5         oXDomainRequest.open('get', 'elseDomain_url', true);
6         oXDomainRequest.send();

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324777914&siteId=291194637