[04] JSONP tutorial, 04jsonp tutorial
JSONP tutorial
Jsonp (JSON with Padding) is a "usage mode" of json that allows a webpage to retrieve information from another domain name (website), that is, to 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.
Same-origin policy, a well-known security policy proposed by Netscape, is now used by all browsers that support JavaScript.
JSONP Application 1. Server JSONP format data
If the customer wants to access: http://www.baidu.com/try/ajax/jsonp.php? Jsonp = callbackFunction.
Assume that the customer expects to return JSON data: ["mermername1", "customername2"].
The data actually returned to the client is displayed as callbackFunction (["mermername1", "customername2"]).
The jsonp. php code of the Server File is:
<?php
header('Content-type: application/json');
// Obtain the callback function name
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
// Json data
$json_data ='["customername1","customername2"]';
// Output data in jsonp format
echo $jsoncallback ."(". $json_data .")";
?>
2. The client implements the callbackFunction function.
<script type="text/javascript">
function onCustomerLoaded(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
>
<Title> JSONP instance </title>
<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.baidu.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
JQuery uses JSONP The above code can be used as an example of jQuery code:
<!DOCTYPE html>
<Title> JSONP instance </title>
<script src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.js"></script>
<body>
<div id="divCustomers"></div>
<script>
$.getJSON("http://www.baidu.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>