资料
环境
- 这里我使用的是
xmapp
集成软件,在本地起的apache
服务进行测试的 - jsonp.php 文件是要放到 xmapp -> htdocs 目录下的
源码
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例</title>
</head>
<body>
<div id="divCustomers"></div>
<script type="text/javascript">
function callbackFunction(result, methodName) {
// result = ["customername1","customername2"]
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://127.0.0.1:8008/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>jsonp.php
1
2
3
4
5
6
7
8
9
header('Content-type: application/json');
//获取回调函数名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json数据
$json_data = '["customername1","customername2"]';
//输出jsonp格式的数据
echo $jsoncallback . "(" . $json_data . ")";浏览器效果图