Creating JSONP Callbacks in JavaScript
Cross-domain requests can pose a challenge in JavaScript development. However, JSONP (JSON with Padding) provides a solution to this issue.
Modifying Your JSON API for JSONP
To enable JSONP capabilities in your JSON API, follow the simple steps below:
Accept a "callback" Parameter in the GET Request:
if(array_key_exists('callback', $_GET)){
Wrap the Callback Function Around Your Data:
$callback.'('.$data.');';
Using PHP as an example, the code below demonstrates these 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
To utilize the JSONP service, you can employ the HTML script tag:
<code class="html"><script> function receiver(data){ console.log(data); } </script> <script src="data-service.php?callback=receiver"></script></code>
The above is the detailed content of How to Create JSONP Callbacks in JavaScript for Cross-Domain Requests?. For more information, please follow other related articles on the PHP Chinese website!