JSONP Tutorial


In this chapter we will introduce you to the knowledge of JSONP.

Jsonp (JSON with Padding) is a "usage mode" of json, which allows web pages to obtain data from other domain names (websites), that is, read data across domains.

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 well-known security policy proposed by Netscape. All browsers that support JavaScript now use this policy.


JSONP application

1. Server-side JSONP format data

If the customer wants to access: http://www.php.cn/try/ajax/jsonp .php?jsonp=callbackFunction.

Suppose the customer expects to return JSON data: ["customername1", "customername2"].

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

The code of the server file jsonp.php is:

<?php
header('Content-type: application/json');
//获取回调函数名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json数据
$json_data = '["customername1","customername2"]';
//输出jsonp格式的数据
echo $jsoncallback . "(" . $json_data . ")";
?>

2. The client implements the 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 code of the client page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>JSONP 实例</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="http://www.php.cn/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>

jQuery uses JSONP

The above code can use jQuery code example:

<!DOCTYPE html>
<html>
<head>
	<title>JSONP 实例</title>
	<script src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.js"></script>	
</head>
<body>
<div id="divCustomers"></div>
<script>
$.getJSON("http://www.php.cn/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>