Home  >  Article  >  Backend Development  >  How to Implement JSONP Callback for Cross-Domain JavaScript?

How to Implement JSONP Callback for Cross-Domain JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 15:41:02401browse

How to Implement JSONP Callback for Cross-Domain JavaScript?

JSONP Callback Implementation for Cross-Domain JavaScript

In order to facilitate communication between different domains, JSONP (JSON with Padding) was introduced. This technique involves creating a callback function that can be used to wrap the JSON data and make it accessible from a different domain. Here's how to implement JSONP in PHP:

Accepting the Callback Parameter

Firstly, in the GET request, we accept a parameter called "callback":

<code class="php">if(array_key_exists('callback', $_GET)){
    ...
}</code>

Wrapping the Callback Function

Next, we wrap the callback JavaScript function around our data. For instance:

<code class="php">$callback = $_GET['callback'];
echo $callback.'('.$data.');';</code>

PHP Example

Here's an example in PHP:

<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>

JavaScript Usage

To utilize the JSONP service, you can employ the script tag:

<code class="html"><script>
    function receiver(data){
        console.log(data);
    }
</script>
<script src="data-service.php?callback=receiver"></script></code>

Concept Explanation

The core idea behind JSONP is to return a JavaScript file that invokes the callback function and provides the JSON object as the first parameter. The json_encode() function in PHP can be used to convert arrays and objects into JSON strings.

By utilizing JSONP, you can establish communication between scripts from different domains, effectively bypassing the same-origin policy limitations and enabling data exchange across domains.

The above is the detailed content of How to Implement JSONP Callback for Cross-Domain JavaScript?. 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