In modern frontend development, it's common to need data from a different domain via AJAX. Due to browser security policies, direct access to resources across domains is restricted. Therefore, solving cross-origin communication has become an essential task. This article introduces two popular PHP-based solutions: JSONP and CORS.
The Same-Origin Policy is a fundamental browser security measure. It restricts JavaScript from accessing resources unless the protocol, domain, and port of the request match those of the current page. For example, if the page is loaded from http://www.example.com/index.html:
JSONP (JSON with Padding) is a legacy method that uses the tag to fetch data from another domain. Since script tags are not restricted by the same-origin policy, the response can be handled using a callback function.
<script type="text/javascript">
function jsonpCallback(data){
alert(data);
}
</script>
<script type="text/javascript" src="http://www.domain2.com/data.php?callback=jsonpCallback"></script>
On the server side, here's how PHP returns the data:
<?php
$data = array('name' => 'Q.syr', 'age' => 24);
echo $_GET['callback'] . '(' . json_encode($data) . ')';
?>
This method is limited to GET requests and carries potential security risks like XSS.
CORS is a W3C standard that enables secure cross-origin requests by allowing servers to specify permitted origins through response headers. It is currently the recommended approach for handling cross-domain communication.
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
Explanation of headers:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var responseText = xmlhttp.responseText;
console.log(responseText);
}
}
xmlhttp.open('GET', 'http://www.domain2.com/data.php', true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send();
This example demonstrates how to make a CORS-enabled request using JavaScript. It supports multiple HTTP methods and is safer than JSONP when handled correctly.
Both methods allow cross-origin requests but differ significantly:
This article introduced two PHP-based cross-origin solutions: JSONP and CORS. Each method has its advantages and limitations. JSONP is quick and simple but insecure and limited in functionality. CORS is secure and supports complex scenarios, making it more suitable for modern web applications. Choose the appropriate method based on your project’s requirements and security considerations.