高德 web API 的 callba 应该怎么用?

2022-05-08 19:35:17 +08:00
 maloneleo88

API 接口 https://lbs.amap.com/api/webservice/guide/api/georegeo

返回数据

{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"北京市朝阳区阜通东大街 6 号","country":"中国","province":"北京市","citycode":"010","city":"北京市","district":"朝阳区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"110105","street":"阜通东大街","number":"6 号","location":"116.482086,39.990496","level":"门牌号"}]}

比如我的 callback=getGPS

$.get('url', getGPS) ???

刚学到回调函数这,回调函数就是写好一个函数,当作参数传给另一个函数调用,那这个 callback 在这个 api 中有什么意义?应该怎么使用?

我现在直接

                   var results = $.get(url, getGeocodes);

                    function getGeocodes() {
                        var tude = results.responseJSON.geocodes[0].location;
                        $("#id_detect_coordinate").val(tude);
                    }
                }

我没有填那个 callback,直接拿到返回数据, 所以那个 callback 到底有什么用?正确使用方法是什么?

1592 次点击
所在节点    JavaScript
4 条回复
maloneleo88
2022-05-08 23:18:56 +08:00
明白了。

```
//回调函数 getGPS
<script>
function getGPS(data) {
//do someting
}
</script>

<script src="请求地址巴拉巴拉&callback=回调函数">
</script>
```
没加 callback 服务器返回的是
```
{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"北京市朝阳区阜通东大街 6 号","country":"中国","province":"北京市","citycode":"010","city":"北京市","district":"朝阳区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"110105","street":"阜通东大街","number":"6 号","location":"116.482086,39.990496","level":"门牌号"}]}
```
加了 callback 以后,服务器返回的是
```
getGPS({"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"北京市朝阳区阜通东大街 6 号","country":"中国","province":"北京市","citycode":"010","city":"北京市","district":"朝阳区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"110105","street":"阜通东大街","number":"6 号","location":"116.482086,39.990496","level":"门牌号"}]})
```

也就是说,服务器直接把 回调函数名+(返回数据) 给返回来了。 所以导致 getGPS(data)接收到的实参对象,所以执行 getGPS(data),此时 data 从形参变实参了,在再回调函数中 do something



问题是,用$.get 直接拿数据不香吗? API 这个回调函数的方式除了解决跨域 还有啥用处?
typedefine
2022-05-09 10:25:47 +08:00
JSONP 这么老的方案 居然还有不知道的
maloneleo88
2022-05-09 11:55:38 +08:00
@typedefine 刚学 汗!
cutemurphy2000
2022-05-12 10:52:31 +08:00
@maloneleo88 哈哈 抱一下·

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/851571

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX