With the popularity of front-end and back-end separation, it has become a common operation in web development for the front-end to call the back-end interface and obtain data through Ajax technology.
However, due to the browser's same-origin policy, web pages from different sources (different protocols, domain names or ports) cannot access each other's own DOM and cookies, which makes cross-domain access a very common requirement. There are many ways to solve this problem.
This article will introduce three ways to implement Ajax cross-domain in PHP.
JSONP (JSON with Padding) is a very popular solution when the front end initiates cross-domain requests. It is actually a way to "cheat" the browser, taking advantage of the fact that the <script>
tag has no cross-domain restrictions to achieve cross-domain access. Its principle is to dynamically generate a JavaScript code snippet for responding to the request on the server side. This code snippet will call a JavaScript function with a specific name (callback function name) and pass the data processed by the server side as a parameter to this function. This achieves the effect of cross-domain access.
The usage of JSONP is as follows:
function handleJsonp(data) { console.log(data); } const script = document.createElement('script'); script.src = 'http://example.com/api?callback=handleJsonp'; document.head.appendChild(script);
<?php $data = array('foo' => 'bar'); $callback = $_GET['callback']; echo sprintf('%s(%s);', $callback, json_encode($data)); ?>
In this code, the return result from the server is a JavaScript code snippet containing a callback function call. After the client gets the data, it will automatically execute the callback function and use the data returned by the server as the parameter of the callback function.
The advantage of JSONP is good compatibility. The compatibility is only limited by the extent to which the browser supports the <script>
tag. However, the disadvantage is that there are security issues because the callback function is in the client. We cannot guarantee that this function executes the logic we expect. If the malicious callback function passes malicious code, there will be a risk of being attacked by XSS.
The proxy mode is another popular cross-domain solution. Its basic idea is to set up a proxy on the server to access the specified URL, and then return the data obtained from the proxy server to the client. In this way, the client can directly access the proxy server from the same origin, and the proxy server then accesses the cross-domain target server and forwards the data returned by the target server.
The proxy mode is used as follows:
fetch('http://example.com/proxy_api') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
<?php $url = 'http://example.com/api'; $data = json_decode(file_get_contents($url), true); echo json_encode($data); ?>
In this code, the client's request is sent to the proxy server. The proxy server returns the data returned by the target server to the client, thus realizing the client's access to cross-domain services.
The advantage of proxy mode is good security, because the client will only access the proxy server from the same source, and the proxy server will then access the cross-domain target server, thus effectively avoiding the security caused by cross-domain access. Risky, but the disadvantage is that additional server-side code needs to be developed, which adds extra work and development costs.
CORS is currently the most popular cross-domain access solution. It sets the response header on the server side to tell the client whether to allow cross-domain access, thereby achieving cross-domain access security control.
CORS is used as follows:
fetch('http://example.com/api', { mode: 'cors' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
<?php header('Access-Control-Allow-Origin: *'); $data = array('foo' => 'bar'); echo json_encode($data); ?>
In this code, the server sets the Access-Control-Allow-Origin:*
response header, indicating that all sources are allowed to access the interface. The client sets mode in the request: 'cors'
parameter to inform the browser that the request will be accessed across domains.
The advantage of CORS is that it supports natively and does not require additional development work. However, its disadvantage is that it does not support IE8/9 and needs to be supported from the server side. It does not support cross-domain access of subdomain names.
The above are three cross-domain methods for PHP to implement Ajax. In actual projects, you should choose the most suitable cross-domain solution according to the specific situation.
The above is the detailed content of Summarize three methods of implementing Ajax cross-domain in PHP. For more information, please follow other related articles on the PHP Chinese website!