AJAX cross-domain solutions

AJAX cross-domain solutions

What is AJAX?

AJAX is a way to get data from the server without refreshing the page, and the core object responsible for the operation of Ajax is the XMLHttpRequest (XHR) object.

The same-origin policy is a major constraint on XHR that sets the restriction of “same domain, same port, same protocol” for communication.
Attempting to access resources outside of the above restrictions will result in a security error unless an approved cross-domain solution is employed.

This solution is called CORS (Cross-Origin Resource Sharing).

Which visits are cross-domain?

  • http://a.com Do not allow access to http://b.com (different domains)
  • http://a.com Do not allow access to https://a.com (same domain, different protocols)
  • http://a.com Do not allow access to http://a.com:8080 (same domain name, different ports)
  • http://a.com Do not allow access to the http://192.168.1.1 (domain name and IP corresponding to the domain name)
  • http://a.a.com Do not allow access to http://b.a.com (same primary domain, different subdomains)

Three solutions:

Solution 1: // Disadvantages: There is a browser compatibility problem

Set in the program: Access-Control-Allow-Origin.

Access-Control-Allow-Origin can be set to *.

//Set up a whitelist that can be accessed
$white_list = ['http://t1.abc.com','http://t2.abc.com'];

$_SERVER['HTTP_ORIGIN'] //Represents the domain name of the requester

$http_origin = '';
if (!empty($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'],$white_list)) {
    $http_origin = $_SERVER['HTTP_ORIGIN'];

    //set header info
    header("Access-Control-Allow-Origin: {$http_origin}");
    header("Access-Control-Allow-Methods", "POST,GET");
    header('Access-Control-Allow-Credentials:true');  //Allow access to cookies
    header('Access-Control-Allow-Headers : X-Requested-With'); //set Headers
}
 

Also: If the request is HTML, add the meta tag to the file.

<meta http-equiv="Access-Control-Allow-Origin" content="*">

Solution 2: //Disadvantages: POST requests are not supported.

Using JSONP to solve cross-domain problems, there are quite a few online articles.

Solution 3: Similar to Solution 1

Modify the Nginx Apache configuration.

#Nginx

http {
  ......
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Headers X-Requested-With;
  add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
  ......
}
#Apache :

<Directory />
    ......
    Header set Access-Control-Allow-Origin *
</Directory>

Solution 4: Add ajax’s crossDomain:true; Options!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *