Home  >  Article  >  Backend Development  >  How to Create JSONP Callbacks in JavaScript for Cross-Domain Requests?

How to Create JSONP Callbacks in JavaScript for Cross-Domain Requests?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 20:54:00730browse

How to Create JSONP Callbacks in JavaScript for Cross-Domain Requests?

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:

  1. Accept a "callback" Parameter in the GET Request:

    if(array_key_exists('callback', $_GET)){
  2. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn