JSONP Tutorial

In this chapter, we will introduce you to JSONP knowledge.

JSONP (JSON with Padding) is a "usage pattern" of JSON that allows web pages to obtain data from other domains (websites), i.e., cross-domain data reading.

Why do we need a special technology (JSONP) to access data from different domains (websites)? This is because of the same-origin policy.

The same-origin policy is a famous security policy proposed by Netscape. Now all browsers that support JavaScript use this policy.


JSONP Application

1. Server-side JSONP format data

For example, if a client wants to access:https://www.example.com/try/ajax/jsonp.php?jsoncallback=callbackFunction。

Assume the client expects to receive data: ["customername1","customername2"].

The data actually returned to the client is displayed as: callbackFunction(["customername1","customername2"]).

The server-side file jsonp.php has the following code:

jsonp.php file code

<?php header('Content-type: application/json'); //Get the callback function name $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']); //JSON data $json_data = '["customername1","customername2"]'; //Output JSONP format data echo $jsoncallback . "(" . $json_data . ")"; ?>

2. Client-side implementation of callbackFunction function

<script type="text/javascript"> function callbackFunction(result, methodName) { var html = '<ul>'; for(var i = 0; i < result.length; i++) { html += '<li>' + result[i] + '</li>'; } html += '</ul>'; document.getElementById('divCustomers').innerHTML = html; } </script>

Page display

<div id="divCustomers"></div>

Complete client page code

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JSONP Example</title> </head> <body> <div id="divCustomers"></div> <script type="text/javascript">
function callbackFunction(result, methodName) { var html = '<ul>'; for(var i = 0; i < result.length; i++) { html += '<li>' + result[i] + '</li>'; } html += '</ul>'; document.getElementById('divCustomers').innerHTML = html; }
</script> <script type="text/javascript" src="https://www.example.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script> </body> </html>

jQuery using JSONP

The above code can be implemented using the jQuery code example:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JSONP Example</title> <script src="https://cdn.static.example.com/libs/jquery/1.8.3/jquery.js"></script> </head> <body> <div id="divCustomers"></div> <script>
$.getJSON("https://www.example.com/try/ajax/jsonp.php?jsoncallback=?", function(data) { var html = '<ul>'; for(var i = 0; i < data.length; i++) { html += '<li>' + data[i] + '</li>'; } html += '</ul>'; $('#divCustomers').html(html); });
</script> </body> </html>
Other extensions