Home > Backend Development > PHP Tutorial > How to Use JSONP for Cross-Domain Communication in JavaScript?

How to Use JSONP for Cross-Domain Communication in JavaScript?

Barbara Streisand
Release: 2024-10-22 14:45:03
Original
938 people have browsed it

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:

  1. Accept the callback parameter in the GET request.
  2. Set the appropriate HTTP headers, including Content-Type and Access-Control headers.
  3. Wrap the callback JavaScript function around the JSON data.
<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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template