jQuery中文參考手冊
/ jQuery JSONP
jQuery JSONP
JSONP 教程
本章節(jié)我們將向大家介紹 JSONP 的知識。
Jsonp(JSON with Padding) 是 json 的一種"使用模式",可以讓網(wǎng)頁從別的域名(網(wǎng)站)那獲取資料,即跨域讀取數(shù)據(jù)。
為什么我們從不同的域(網(wǎng)站)訪問數(shù)據(jù)需要一個特殊的技術(shù)(JSONP )呢?這是因為同源策略。
同源策略,它是由Netscape提出的一個著名的安全策略,現(xiàn)在所有支持JavaScript 的瀏覽器都會使用這個策略。
JSONP 應(yīng)用
1. 服務(wù)端JSONP格式數(shù)據(jù)
如客戶想訪問 : 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 文件代碼
實例
<?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 . ")"; ?>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
2. 客戶端實現(xiàn) callbackFunction 函數(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>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
頁面展示
客戶端頁面完整代碼
實例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <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.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
jQuery 使用 JSONP
以上代碼可以使用 jQuery 代碼實例:
實例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JSONP 實例</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>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例