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

Susan Sarandon
Release: 2024-10-22 20:54:00
Original
787 people have browsed it

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)){
    Copy after login
  2. Wrap the Callback Function Around Your Data:

    $callback.'('.$data.');';
    Copy after login

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

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

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!

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