There are three ways for ajax to solve cross-domain problems: 1. Use a proxy to obtain content under other domain names through the background, and then return the obtained content to the front end so that it is under the same domain name; 2. Use JSONP to The method only supports get requests, and loads data into js files on the remote server for client calling and further processing; 3. Use "LHttpRequest Level 2", the syntax is "header('Access-Control-Allow-Origin:* ')".
The operating environment of this article: windows10 system, javascript1.8.5&&html5 version, Dell G3 computer.
Domain: The domain is the security boundary of the WIN2K network system. We know that the most basic unit of a computer network is a "domain". This is not unique to WIN2K, but Active Directory can run through one or more domains. On an independent computer, a domain refers to the computer itself. A domain can be distributed in multiple physical locations. At the same time, a physical location can be divided into different network segments into different domains. Each domain has its own security policy and its relationship with Trust relationships with other domains. When multiple domains are connected through trust relationships, Active Directory can be shared by multiple trusting domains.
Because you need to use AJAX to request requests under other domain names at work, access will be denied. This is because based on security considerations, AJAX can only access local resources and cannot access cross-domain resources.
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 consider it unsafe and deny access.
There are several situations where cross-domain problems may occur:
A total of three solutions are summarized: proxy, JSONP, and XHR2 (XMLHttpRequest Level 2).
The first method is proxy: This method is to obtain the content under other domain names through the background (ASP, PHP, JAVA, ASP.NET), and then put the obtained content Return to the front end, so because it is under the same domain name, there will be no cross-domain problems.
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+")"); //将返回的文本数据转换JSON对象 document.getElementById("box").innerHTML = resultObj.name+":"+resultObj.sex; //将返回的内容显示在页面中 } } request.open("POST","proxy.php",true); request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); request.send("name=吕铭印&sex=男");
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 the php code to obtain the proxy.js file under localhost:63342.
proxy.js code
{ name : "吕铭印", sex : "男" }
proxy.html running results
At this point, the proxy is used to access files between different domains.
First use AJAX in proxy.html to access the proxy.php file in the background. Then after proxy.php receives the request, it accesses the proxy.js file in localhost:63342. After obtaining the content of proxy.js, Return the content to the front-end page, which implements cross-domain functionality.
If you want to access multiple cross-domain files, you can tell the background proxy.php file the address of the file to be accessed in the form of a parameter.
The second method JSONP (only supports GET requests): Later, people discovered that when calling Js files, they are not affected by cross-domain, so the second solution was derived.
is to load the data into a js file on the remote server for client calling and further processing.
jsonp.html
var url = "http://localhost:63342/ajax/jsonp.php?name=吕铭印&sex=男&callbackname=jsonp_callback"; //访问localhost:63342下的jsonp.php var scriptTag = document.createElement("script"); //创建一个script标签 scriptTag.setAttribute("src",url); //设置script的src属性 document.body.appendChild(scriptTag); //将script标签添加到body中 //回调函数 var jsonp_callback = function(resultObj){ document.getElementById("box").innerHTML = resultObj.name+":"+resultObj.sex; } jsonp.php $name = $_GET["name"]; $sex = $_GET["sex"]; $callbackname = $_GET["callbackname"]; //回调函数名称 echo "$callbackname({name:'$name',sex:'$sex'})";
Implementation principle: Since using script tags to call remote js files is not affected by cross-domain, you can create a script tag and access the remote file through the src attribute. .
Actually, this does not belong to AJAX, but it can achieve functions similar to AJAX.
The third method XMLHttpRequest Level 2: XMLHttpRequest Level 2 provided by HTML5 has implemented cross-domain access and other new features
This needs to be done on the remote server side Add the following code
header('Access-Control-Allow-Origin:*'); //*代表可访问的地址,可以设置指定域名 header('Access-Control-Allow-Methods:POST,GET');
so that you can use regular AJAX code on the client side.
Summary: Proxy implementation is the most troublesome, but it is the most widely used. Any browser that supports AJAX can use this method.
JSONP is relatively simple, but it only supports GET calls.
XHR2 is the simplest, but it only supports HTML5. If you are developing for mobile terminals, you can choose to use XHR2.
[Related tutorial recommendations: AJAX video tutorial]
The above is the detailed content of There are several ways to solve cross-domain problems with ajax. For more information, please follow other related articles on the PHP Chinese website!