Latest web development tutorials

JSONP Tutorial

This chapter we will introduce JSONP knowledge.

Jsonp (JSON with Padding) is a json "use mode" that allows it to obtain information from other web domains (websites), that cross-domain data is read.

Why do we need a special technique different domain (website) to access data from (JSONP) it? This is because the same origin policy.

Origin policy, it is a well-known security policy proposed by Netscape, now all browsers support JavaScript will use this strategy.


JSONP Applications

1. The server JSONP format data

If customers want to access: http://www.w3big.com/try/ajax/jsonp.php?jsonp=callbackFunction.

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

Truly returned to the client's data is displayed as: callbackFunction ([ "customername1", "customername2"]).

Server file jsonp.php code:

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

2. The client function to achieve callbackFunction

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

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

Clients complete code 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.w3big.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>

jQuery using JSONP

The above code can use jQuery code examples:

<!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.w3big.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>