JSONP 教程

2023-04-15 16:32 更新

本章節(jié)我們將向大家介紹 JSONP 的知識(shí)。

Jsonp(JSON with Padding) 是 json 的一種"使用模式",可以讓網(wǎng)頁(yè)從別的域名(網(wǎng)站)那獲取資料,即跨域讀取數(shù)據(jù)。

為什么我們從不同的域(網(wǎng)站)訪(fǎng)問(wèn)數(shù)據(jù)需要一個(gè)特殊的技術(shù)(JSONP )呢?這是因?yàn)橥床呗浴?/p>

什么是同源策略?它是由Netscape提出的一個(gè)著名的安全策略,現(xiàn)在所有支持 JavaScript 的瀏覽器都會(huì)使用這個(gè)策略。

Jsonp 的實(shí)現(xiàn)原理是利用 <script> 標(biāo)簽可以獲取不同源資源的特點(diǎn),來(lái)達(dá)到跨域訪(fǎng)問(wèn)某個(gè)資源的目的。


JSONP 應(yīng)用

1. 服務(wù)端JSONP格式數(shù)據(jù)

如客戶(hù)想訪(fǎng)問(wèn) :? /try/ajax/jsonp.php?jsonp=callbackFunction?。

假設(shè)客戶(hù)期望返回JSON數(shù)據(jù):?["customername1","customername2"]?。

真正返回到客戶(hù)端的數(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. 客戶(hù)端實(shí)現(xiàn) callbackFunction 函數(shù)

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

頁(yè)面展示

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

客戶(hù)端頁(yè)面完整代碼

<!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="/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" rel="external nofollow" ></script> 
</head>
<body>
<div id="divCustomers"></div>
<script>
$.getJSON("/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> 


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)