JSONP 是一种无需考虑跨域问题即可传送 JSON 数据的方法。
JSONP 不使用 XMLHttpRequest 对象。
JSONP 使用 <script> 标签取而代之。
JSONP 简介
JSONP 指的是 JSON with Padding。
从另一个域请求文件会引起问题,由于跨域政策。
从另一个域请求外部脚本没有这个问题。
JSONP 利用了这个优势,并使用 script 标签替代 XMLHttpRequest 对象。
<script src="demo_jsonp.php">
JSONP 应用
服务端 JSONP 格式数据
如客户想访问 : 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 . ")";
?>
客户端:
<!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="https://www.xxxx.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>
jQuery 使用 JSONP:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例</title>
<script src="https://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script>
</head>
<body>
<div id="divCustomers"></div>
<script>
$.getJSON("https://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>