Home >Web Front-end >JS Tutorial >Detailed introduction to AJAX cross-domain (code example)
The content of this article is a detailed introduction (code example) about AJAX cross-domain. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
There are two commonly used solutions to AJAX's cross-domain problems. Record them briefly and check the reference materials for details. The following example creates two domain names for testing, www.test.com and www.example.com.
Same Origin Policy
The Same Origin Policy restricts how documents or scripts loaded from one source interact with resources from another source. This is a critical security mechanism for isolating potentially malicious files.Two pages, if the domain name, protocol,port are the same, they are from the same source, and there is no problem with the interaction between them. The same-origin policy is a very important security mechanism, but sometimes it is necessary to break through this mechanism, which requires cross-domain.
JSONP
JSONP is a very common method. It is implemented using the principle that the tag has no cross-domain restrictions. The following is an example of using JQuery in www.test.com
$.ajax( { url:'//www.example.com', data:{name:'tom'}, type:'get', dataType:'jsonp', jsonp: "callback", success:function(data) { console.log(data) } })
The following is the PHP processing of www.example.com
<?php $callback = $_GET['callback']; $name = $_GET['name']; // 处理数据 $data = md5($name); echo $callback . '(' . json_encode($data) . ')';
CORS
CORS (Cross-origin resource sharing), the cross-origin resource sharing standard allows web application servers to perform cross-domain access control. Compared with JSONP which only supports GET, CORS supports more HTTP requests and is simpler and more secure. However, CORS may have compatibility issues.
The following is the PHP processing of sending an AJAX request to www.test.com
$.ajax( { url:'//www.example.com', data:{name:'tom'}, type:'post', dataType:'json', success:function(data) { console.log(data) } });
www.example.com
<?php header("Access-Control-Allow-Origin: http://www.test.com"); $name = $_POST['name']; // 处理数据 $data = md5($name); echo json_encode($data);
The above is the detailed content of Detailed introduction to AJAX cross-domain (code example). For more information, please follow other related articles on the PHP Chinese website!