JSONP一种使用<script>元素获取数据的方法
现在很多厂商比如,百度、谷歌在调用api接口时早已开始使用json数据。 但是古老的XMLHttpRequest设计时,为了安全性,不能使用跨站数据(就是调用其它的网站的数据)
如果需要访问由远程服务器上一个web服务托管的json数据,则要使用JSONP。
假设,我要进行百度地图坐标转换,这是文档http://developer.baidu.com/map/changeposition.htm
运行示例http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924;114.21892734521,29.575429778924&from=1&to=1
浏览器打开得到返回值 (注意当前返回错误,本文只是随便找个例子用来讲解) {"status":22,"message":"param error:to illegal,not support such coord type","result":[]} 那么我们该如何来让我们的页面程序获取这个值呢?
在示例链接中加入 callback=GetValue
然后新建html页面 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script> var getVal; function GetValue(Value) { getVal = Value; alert("ok"); } </script> </head> <body> <script src="http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924&from=1&to=1&callback=GetValue"> </script> </body> </html> !注意html页面中新建的GetValue函数 通过<script>标签调用示例链接产生GetValue值时就会弹窗
然后通过火狐firebug进入控制台查看GetValue的参数传递给getVal的值 Object { status=22,message="param error:to illegal,...support such coord type",result=[0]}OK,就讲到这里 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |