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;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,就讲到这里


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赫敏璋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值