Home >Backend Development >PHP Tutorial >How to Use JSONP for Cross-Domain Communication in JavaScript?
How to Create JSONP in JavaScript for Cross-Domain Communication
When dealing with cross-origin requests, the notorious same-origin policy can become a hindrance. However, JSONP (JSON with Padding) was designed as a clever solution to bypass this restriction.
How Does JSONP Work?
JSONP cleverly leverages the behavior of web browsers. By providing a parameter called callback in the GET request, you allow the server to wrap the JSON data in a JavaScript function call. The browser then executes the function, passing the JSON data as an argument.
Creating the Server-Side Callback API in PHP
If you're using PHP on the server, implement the following steps:
<code class="php"><?php $data = '{}'; // json string if(array_key_exists('callback', $_GET)){ header('Content-Type: text/javascript; charset=utf8'); header('Access-Control-Allow-Origin: http://www.example.com/'); header('Access-Control-Max-Age: 3628800'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); $callback = $_GET['callback']; echo $callback.'('.$data.');'; }else{ // normal JSON string header('Content-Type: application/json; charset=utf8'); echo $data; } ?></code>
Using the JSONP Service on the Client-Side
To utilize the JSONP service on the client-side, follow this example:
<code class="html"><script> function receiver(data){ console.log(data); } </script> <script src="data-service.php?callback=receiver"></script></code>
This script creates a receiver function to handle the incoming JSON data, then dynamically loads the data-service.php file, providing the callback function as an argument.
The above is the detailed content of How to Use JSONP for Cross-Domain Communication in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!