gpt4 book ai didi

javascript - 从 API 调用 JSON 元素并将结果作为字符串返回

转载 作者:行者123 更新时间:2023-11-30 08:46:20 24 4
gpt4 key购买 nike

我正在尝试从 API 中专门调用一个元素(国家/地区),我希望它以字符串形式返回,我将在下面详细说明

用户的输入:
美国纽约州纽约市

使用的API:
http://maps.google.com/maps/api/js?sensor=true&libraries=places

期望的结果:
美国/美国/美国

JSON 不知道它叫什么:
https://maps.googleapis.com/maps/api/geocode/json?address=New%20York,%20NY,%20United%20States&sensor=true

我对如何去做有点迷茫,但这是我尝试过的:

<html>  
<head></head>
<title>Project 9</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn1 ").click(function() {
var address=encodeURI($('#userInput').val());
var url='https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=true';
$.getJSON(url, function(data){
var shortname=data.results[0].address_components[3].short_name;
var longname=data.results[0].address_components[3].long_name;
alert(shortname+' '+longname);
});
});
});
</script>
<body>
<input type="text" value="sdfasd" name="userInput" id="userInput" />
<input type="button" id="btn1" value="Load Data" />
</body>
</html>

我更新了问题,感谢您的所有回答,但是我注意到在某些输入中,它不会返回国家,而是返回地址组件索引 3 中的对象我们如何限制它只返回国家?谢谢

它能像这样工作吗?

  var shortname=data.results[0].address_components[country].short_name;
var longname=data.results[0].address_components[country].long_name;
alert(shortname+' '+longname);

最佳答案

将返回 json 的 url 传递给 getJSON 函数。参数数据将保存您从服务器获得的响应 json。

你可以看到它包含一个名为“results”的字段,它是一个数组。所以拿 data.results[0] 。在其中,字段 formatted_address 包含您的值。

var url = "https://maps.googleapis.com/maps/api/geocode/json?address=New%20York,%20NY,%20United%20States&sensor=true"  

$.getJSON(url, function(data)
{
alert(data.results[0].formatted_address)

});

关于javascript - 从 API 调用 JSON 元素并将结果作为字符串返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21722911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com