JSONP一种使用<script>元素获取数据的方法

前端之家收集整理的这篇文章主要介绍了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


浏览器打开得到返回值 (注意当前返回错误,本文只是随便找个例子用来讲解)

  1. {"status":22,"message":"param error:to illegal,not support such coord type","result":[]}

那么我们该如何来让我们的页面程序获取这个值呢?


在示例链接中加入

  1. callback=GetValue


然后新建html页面

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <Meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5. <title></title>
  6. <script>
  7.  
  8.  
  9. var getVal;
  10. function GetValue(Value)
  11. {
  12. getVal = Value;
  13. alert("ok");
  14. }
  15. </script>
  16. </head>
  17. <body>
  18. <script src="http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924&from=1&to=1&callback=GetValue">
  19. </script>
  20. </body>
  21. </html>

!注意html页面中新建的GetValue函数

通过<script>标签调用示例链接产生GetValue值时就会弹窗


然后通过火狐firebug进入控制台查看GetValue的参数传递给getVal的值

  1. Object { status=22,message="param error:to illegal,...support such coord type",result=[0]}
OK,就讲到这里

猜你在找的Json相关文章