【问题标题】:Call JSON element from an API and return result as string从 API 调用 JSON 元素并将结果作为字符串返回
【发布时间】:2014-03-10 11:34:14
【问题描述】:

我正在尝试从 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);

【问题讨论】:

  • 将答案标记为正确也会对其他人有所帮助。 :)

标签: javascript jquery json google-maps


【解决方案1】:

将返回 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)

 });

【讨论】:

    【解决方案2】:
    <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(event) {
    url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + 
    encodeURI($('#userInput').val()) + '&sensor=true';
     $.getJSON(url, function(data)
     {
         //here we process the json. and whatever we want after the call came back from api
         // notice the data arg that i putted above.
    alert(data.results[0].address_components[2].short_name);
    // this will alert "US"
    
     });
     });
     });
    </script>         
    <body>
    <input type="text" value="New York, NY, United States" name="userInput" id="userInput" />
      <input type="button" id="btn" value="Load Data" />
    </body>
    

    干杯。

    【讨论】:

      【解决方案3】:

      首先,阅读这篇文章。

      getJSON 签名如下:

      jQuery.getJSON( url [, data ], callback);
      

      回调函数签名如下:

      callback( data, textStatus, jqXHR );
      
      • data 是所需的 json 对象
      • textStatus 是一个字符串,用于检查 ajax 请求的状态
      • jqXHR 是实际的 ajax 请求对象

      所以如果你有数据作为查询字符串发送,比如地址作为参数,你可以这样发送:

      var url = "https://maps.googleapis.com/maps/api/geocode/json"
      var data = {
          address: "New York, NY, United States",
          sensor: true
      };
      jQuery.getJSON(url, data, function(data, status, xhr){
          console.log(data.results);
          for(var i=0;i<data.results.length;i++){
              var result = data.results[i];
      
              //all addresses as a string
              console.log(result.formatted_address);
      
              //info about your addresses which is an array
              console.log(result.address_components);
      
              console.log(result.geometry);
              /*the result.geometry is like:
      
              bounds: Object
              location: Object
              location_type: "APPROXIMATE"
              viewport: Object
                  northeast: Object
                      lat: 40.9152555
                      lng: -73.700272
                  southwest: Object
                      lat: 40.496006
                      lng: -74.2557349
              */
      
          }
      })
      

      【讨论】:

        【解决方案4】:

        如下修改你的代码

        $(document).ready(function() {
             $("#btn1 ").click(function(event) {
               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[2].short_name
                  var longname=data.results[0].address_components[2].long_name
                  alert(shortname+' '+longname);
             });
           });
        });
        

        【讨论】:

          【解决方案5】:
          <html>  
          <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 (event) {
                  // $.getJSON(url,data,success(data,status,xhr))
                  var url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=true';
                  var data = { address: 'New York,NY,United States'};
                  $.getJSON(url, data, function (result) {
                      var components = result.results[0].address_components;
                      for (var i = 0; i < components.length; i++) {
                          var c = components[i];
                          if (c.types && c.types.indexOf('country') >= 0) {
                              // long_name contains country long name and 'short_name' contains country's abbreviated name
                              console.log(c.long_name + '/' + c.short_name);
                              break;
                          }
                      }                    
                  });
              });
          });
          </script>
          </head>
          
          <body>
              <input type="button" id="btn1" value="Load Data" />
          </body>
          

          【讨论】:

            猜你喜欢
            • 2013-02-24
            • 2016-04-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多