jQuery JSONP
JSONP 教程
本章節(jié)我們將向大家介紹 JSONP 的知識(shí)。
Jsonp(JSON with Padding) 是 json 的一種"使用模式",可以讓網(wǎng)頁(yè)從別的域名(網(wǎng)站)那獲取資料,即跨域讀取數(shù)據(jù)。
為什么我們從不同的域(網(wǎng)站)訪問(wèn)數(shù)據(jù)需要一個(gè)特殊的技術(shù)(JSONP )呢?這是因?yàn)橥床呗浴?/p>
同源策略,它是由Netscape提出的一個(gè)著名的安全策略,現(xiàn)在所有支持JavaScript 的瀏覽器都會(huì)使用這個(gè)策略。
JSONP 應(yīng)用
1. 服務(wù)端JSONP格式數(shù)據(jù)
如客戶想訪問(wèn) : http://www.runoob.com/try/ajax/jsonp.php?jsonp=callbackFunction。
假設(shè)客戶期望返回JSON數(shù)據(jù):["customername1","customername2"]。
真正返回到客戶端的數(shù)據(jù)顯示為: callbackFunction(["customername1","customername2"])。
服務(wù)端文件jsonp.php代碼為:
jsonp.php 文件代碼
實(shí)例
<?php header('Content-type: application/json'); //獲取回調(diào)函數(shù)名 $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']); //json數(shù)據(jù) $json_data = '["customername1","customername2"]'; //輸出jsonp格式的數(shù)據(jù) echo $jsoncallback . "(" . $json_data . ")"; ?>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
2. 客戶端實(shí)現(xiàn) callbackFunction 函數(shù)
實(shí)例
<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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
頁(yè)面展示
客戶端頁(yè)面完整代碼
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JSONP 實(shí)例</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.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
jQuery 使用 JSONP
以上代碼可以使用 jQuery 代碼實(shí)例:
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JSONP 實(shí)例</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script> </head> <body> <div id="divCustomers"></div> <script> $.getJSON("http://www.runoob.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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例