jsonp应用
Posted 明烟雨任
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jsonp应用相关的知识,希望对你有一定的参考价值。
1.服务端jsonp格式数据
如客户想访问 : http://www.runoob.com/try/ajax/jsonp.php?jsonp=callbackFunction。
假设客户期望返回JSON数据:["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 .")";
?>
2.客户端实现callbackFunction函数
<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>
客户端实现的完整代码
以上是关于jsonp应用的主要内容,如果未能解决你的问题,请参考以下文章