本章節我們将向大家介紹 JSONP 的知識。
Jsonp(JSON with Padding) 是 json 的一種"使用模式",可以讓網頁從别的域名(網站)那擷取資料,即跨域讀取資料。
為什麼我們從不同的域(網站)通路資料需要一個特殊的技術( JSONP )呢?這是因為同源政策。
同源政策,它是由 Netscape 提出的一個著名的安全政策,現在所有支援 JavaScript 的浏覽器都會使用這個政策。
如客戶想通路 : https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction。
假設客戶期望傳回資料:["customername1","customername2"]。
真正傳回到用戶端的資料顯示為: callbackFunction(["customername1","customername2"])。
服務端檔案 jsonp.php 代碼為:
<?php
header('Content-type: application/json');
//擷取回調函數名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json資料
$json_data = '["customername1","customername2"]';
//輸出jsonp格式的資料
echo $jsoncallback . "(" . $json_data . ")";
?>
<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>
<html>
<head>
<meta charset="utf-8">
<title>JSONP 執行個體</title>
</head>
<body>
<script type="text/javascript" src="https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>
以上代碼可以使用 jQuery 代碼執行個體:
<script src="https://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script>
<script>
$.getJSON("https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?", function(data) {
for(var i = 0; i < data.length; i++)
html += '<li>' + data[i] + '</li>';
$('#divCustomers').html(html);
});