Three methods for cross-origin implementation in AJAX (proxy, JSONP, XHR2) and jsonpxhr2
Domain: the domain is the security boundary of the WIN2K network system. We know that the most basic unit of a computer network is "Domain", which is not unique to WIN2K, but the Active Directory can run through one or more domains. On an independent computer, the domain refers to the computer itself. A domain can be distributed across multiple physical locations. At the same time, a physical location can be divided into different network segments for different domains, each domain has its own security policy and its trust relationship with other domains. When multiple domains are connected through the trust relationship, the Active Directory can be shared by multiple trust domain domains.
In work, AJAX is required to request requests under other domain names, but access is rejected because AJAX can only access local resources based on security considerations, cross-origin access is not allowed.
For example, if your website domain name is aaa.com and you want to request the content in the bbb.com domain name through AJAX, the browser will think it is insecure, so access is denied.
Cross-origin problems may occur in the following situations:
The background searched for a solution on Baidu to solve this problem. Three solutions were summarized: proxy, JSONP, and XHR2 (XMLHttpRequest Level 2 ).
The first method is proxy: This method is implemented through the background (ASP, PHP, JAVA, ASP. NET) to obtain the content under other domain names, and then return the obtained content to the front-end, so that because the same domain name, so there will be no cross-origin issues.
Implementation Code: Create an AJAX request (the page address is http: // localhost/ajax/proxy.html)
Var request = null; if (window. XMLHttpRequest) {request = new XMLHttpRequest ();} else {request = new ActiveXObject ("Microsoft. XMLHttp ");} request. onreadystatechange = function () {console. log (this. readyState); if (this. readyState === 4 & this. status = 200) {var resultObj = eval ("(" + this. responseText + ")"); // converts the returned text data to the JSON object document. getElementById ("box "). innerHTML = resultObj. name + ":" + resultObj. sex; // display the returned content on the page} request. open ("POST", "proxy. php ", true); request. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); request. send ("name = LU mingyin & sex = male ");
Create an AJAX request.
Proxy. php code
header("Content-type:text/html;charset=utf-8");$url = "http://localhost:63342/ajax/proxy.js";$contents = file_get_contents($url);echo $contents;
Use php code to obtain the proxy. js file under localhost: 63342.
Proxy. js Code
{Name: "Lu mingyin", sex: "male "}
Proxy.html running result
So far, the proxy is used to access files between different domains.
First, access the background proxy using AJAX in proxy.html. PHP file, and then proxy. after receiving the request, php accesses the proxy in localhost: 63342. js file, get proxy. after js content, the content is returned to the front-end page, which implements the cross-origin function.
If you want to access multiple cross-origin files, you can tell the address of the file to be accessed by the background proxy. php file in the form of parameters.
The second method is JSONP (only GET requests are supported). Later, it was found that the Js file is not affected by cross-origin calling, and the second method is derived.
Data is loaded into js files on the remote server for the client to call and further process.
Jsonp.html
Var url = "http: // localhost: 63342/ajax/jsonp. php? Name = LU mingyin & sex = male & callbackname = jsonp_callback "; // access jsonp under localhost: 63342. phpvar scriptTag = document. createElement ("script"); // create a script tag scriptTag. setAttribute ("src", url); // set the src attribute document of the script. body. appendChild (scriptTag); // Add the script tag to the body // callback function var jsonp_callback = function (resultObj) {document. getElementById ("box "). innerHTML = resultObj. name + ":" + resultObj. sex ;}
Jsonp. php
$ Name = $ _ GET ["name"]; $ sex = $ _ GET ["sex"]; $ callbackname = $ _ GET ["callbackname"]; // callback function name echo "$ callbackname ({name: '$ name', sex:' $ sex '})";
Jsonp.html running result:
Implementation principle: Since the use of script tags to call a remote js file is not affected by cross-origin, you can create a script tag and access the remote file through the src attribute.
In fact, this does not belong to AJAX, but it can implement functions similar to AJAX.
Method 3 XMLHttpRequest Level 2: XMLHttpRequest Level 2 provided by HTML5 has implemented cross-origin access and some other new features
Add the following code on the remote server:
Header ('access-Control-Allow-Origin: * '); // * indicates the accessible address. You can set the specified domain name header ('access-Control-Allow-Methods: POST, GET ');
In this way, you can use the regular AJAX code on the client.
Conclusion: proxy implementation is the most troublesome, but most widely used. This method can be used by any browser that supports AJAX.
JSONP is relatively simple, but only the GET method is supported.
XHR2 is the simplest, but only supports HTML5. If you are using mobile development, you can choose XHR2.
The above section describes three methods for implementing cross-origin AJAX (proxy, JSONP, XHR2). I hope this will help you!
Articles you may be interested in:
- Cross-origin and JSONP of AJAX (the function of automatically adding a short address to an article)
- Use of ajax jsonp for cross-origin requests
- Jquery ajax jsonp cross-origin call instance code
- JSONP cross-origin GET requests solve Ajax cross-origin access problems