當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSON 使用 教程
生活随笔
收集整理的這篇文章主要介紹了
JSON 使用 教程
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JSONP 教程
本章節(jié)我們將向大家介紹 JSONP 的知識(shí)。
Jsonp(JSON with Padding) 是 json 的一種"使用模式",可以讓網(wǎng)頁從別的域名(網(wǎng)站)那獲取資料,即跨域讀取數(shù)據(jù)。
為什么我們從不同的域(網(wǎng)站)訪問數(shù)據(jù)需要一個(gè)特殊的技術(shù)(JSONP )呢?這是因?yàn)橥床呗浴?/p>
同源策略,它是由Netscape提出的一個(gè)著名的安全策略,現(xiàn)在所有支持JavaScript 的瀏覽器都會(huì)使用這個(gè)策略。
JSONP 應(yīng)用
1. 服務(wù)端JSONP格式數(shù)據(jù)
如客戶想訪問 : http://www.rm5u.com/try/ajax/jsonp.php?jsonp=callbackFunction。
假設(shè)客戶期望返回JSON數(shù)據(jù):["customername1","customername2"]。
真正返回到客戶端的數(shù)據(jù)顯示為: callbackFunction(["customername1","customername2"])。
服務(wù)端文件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. 客戶端實(shí)現(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>頁面展示
<div id="divCustomers"></div>客戶端頁面完整代碼
<!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 實(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.rm5u.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script> </body> </html>jQuery 使用 JSONP
以上代碼可以使用 jQuery 代碼實(shí)例:
<!DOCTYPE html> <html> <head><title>JSONP 實(shí)例</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.rm5u.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è)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的JSON 使用 教程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 可缺省的CSS布局——张鑫旭
- 下一篇: JS_理解函数参数按值传递