Ajax implements Cross-domain three ways (proxies, JSONP,XHR2) _ajax related

Source: Internet
Author: User
Tags ming php file script tag

Domain: 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 a stand-alone computer, the domain refers to the computer itself, a domain can be distributed across multiple physical locations, while a physical location can divide different network segments into different domains, each with its own security policy and its trust relationship with other domains. When multiple domains are connected through a trust relationship, the Active Directory can be shared by multiple trusted domain domains.

Because of the need to use AJAX to request requests under other domain names at work, access is denied because, based on security considerations, Ajax can access only local resources, not across domains.

For example, your website domain name is aaa.com, want to request the content of bbb.com domain name through Ajax, the browser will think it is unsafe, so deny access.

There are several scenarios in which cross-domain problems occur:

Baidu in the background to find solutions to solve this problem, summed up a total of three options: Agents, JSONP, XHR2 (XMLHttpRequest Level 2).

The first method of proxy: This way is through the background (ASP, PHP, JAVA, asp.net) to get the contents of other domain names, and then return to the front-end, so that under the same domain name, so there will be no cross-domain problems.

Implementation code: Create an AJAX request (page address: 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; Displays the returned content in the page
}
request.open ("POST", "proxy.php", true);
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

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);

Use the PHP code to get the Proxy.js file under localhost:63342.

Proxy.js Code

{
name: "Lu Ming Yin",
Sex: "Male"

Proxy.html Run Results


At this point, using a proxy enables you to access files between different domains.

First, proxy.html use Ajax to access the background proxy.php files, and then proxy.php receive requests to access localhost : The Proxy.js file in 63342, after obtaining the content of the Proxy.js, returns the content to the front-end page, which enables Cross-domain functionality.

If you want to access multiple Cross-domain files, you can tell the address of the file to be accessed by the background proxy.php file as a parameter.

The second method JSONP (only supports GET requests): Later, it was discovered that when the JS file was invoked, it was unaffected by Cross-domain, which spawned the second scenario.

is in the remote server to load the data into the JS file for client calls and further processing.

Jsonp.html

var url = "Http://localhost:63342/ajax/jsonp.php?name= lu Ming Yin &sex= male &callbackname=jsonp_callback"; Access the jsonp.php
var scripttag = document.createelement ("script") under localhost:63342;//Create a SCRIPT tag
Scripttag.setattribute ("src", url); Sets the SRC attribute of the script
Document.body.appendChild (scripttag);//Add script tags to 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

Jsonp.html Run Result:


Implementation principle: Because using the script tag to invoke a remote JS file is not unaffected by cross-domain, you can access the remote file through the SRC attribute by creating a script tag.

This does not belong to Ajax, but it can achieve AJAX-like functionality.

The third approach XMLHttpRequest level 2:HTML5 provides XMLHttpRequest level 2 has enabled Cross-domain access and some other new features

This requires adding the following code on the remote server side

Header (' access-control-allow-origin:* '); * Represents an accessible address, you can set the specified domain name

This way, you can use regular AJAX code on the client.

Summary: The agent implementation is the most troublesome, but the most widely used, any AJAX-enabled browser can use this approach.

JSONP is relatively simple, but only get-way calls are supported.

XHR2 is the simplest, but only support HTML5, if you are mobile end development, you can choose to use XHR2.

The above is a small series of Ajax to introduce the implementation of the Cross-domain three ways (agent, JSONP,XHR2), I hope to help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.