js Cross Domain Resource Sharing Fundamentals

  • 2021-07-01 06:30:24
  • OfStack

This article introduces javascript cross-domain resource sharing in detail for your reference. The specific contents are as follows

1. Why do you propose cross-domain resource sharing (CORS)?
Because XHR implements ajax with the security restriction that an XHR object can only access resources in the same domain as the page that contains it

2. How to achieve cross-domain? (Cross-browser)


  //  Create and return across browsers CORS Object 
  // param method :  Mode of request , get or post
  // param url :  Cross-domain requested url
  // return xhr :  Cross-domain resource object returned 
  function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr){
      xhr.open(method, url, true);  // CORS All through asynchronous requests 
    } else if (typeof XDomainRequest != "undefined"){  // IE
      vxhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      xhr = null;
    }
    return xhr;
  }
  var request = createCORSRequest("get", "http://localhost/aaa/dome2.php");
  if (request){
    //  Used for substitution onreadystatechange  If the test is successful, it means that the data is accepted 
    request.onload = function(){
      //  Processing the information of the response 
      alert(request.responseText);  //  Get the content of the response 
    };
    //  Used for substitution onreadystatechange  Detect errors. 
    request.onerror = function(){
      //  Processing the information of the response 
    };
    //  Used to stop an ongoing request. 
    request.onabort = function(){
      //  Processing the information of the response 
      alert(request.responseText);
    };
    //  Send requests across domains 
    request.send();
  }

The above is the whole content of this paper, hoping to help everyone's study.


Related articles: