JSON解析与jQuery循环 [英] json parse with jQuery loop

查看:114
本文介绍了JSON解析与jQuery循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码附在下面,尽管它是较大代码的一部分

hi my code is attached below, though its a part of bigger code

<html>
<head>
<style>
#results{margin-top:100px; width:600px; border:1px solid #000000; background-color:#CCCCCC; min-height:200px;}
</style>


<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<div id="results"></div>

<script>

var input="Taj Mahal India";

var url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + input + "&sensor=false";

   var check = $.getJSON(url, function (data) {
            console.log("inside getjson");
            console.log(data);
            $.each(data.results.address_components, function(i,inside){

             if(inside.types[0]=="route"){
         $("#results").append('<p> route : '+this.long_name +'</p>');
    }   
    if(inside.types[0]=="locality"){
        $("#results").append('<p> locality : '+this.long_name +'</p>');
    } 

    if(inside.types[0]=="administrative_area_level_2"){
        $("#results").append('<p> administrative area 2 : '+this.long_name +'</p>');
    }   
    if(inside.types[0]=="administrative_area_level_1"){
        $("#results").append('<p> administrative area 1 : '+this.long_name +'</p>');
    } 

    if(inside.types[0]=="country"){
        $("#results").append('<p> country : '+this.long_name +'</p>');
    } 

    }); 
    });

    </script>

    </body>

    </html>

问题是它不起作用.我强烈怀疑我在$.each(data.results.address_components, function(i,inside)行中做错了什么.

The problem is that it doesn't work. I have a strong doubt that i have done something wrong in $.each(data.results.address_components, function(i,inside) line.

泰姬陵印度的JSON在这里 http://maps.googleapis.com/maps/api/geocode/json?address=Taj%20Mahal%20India&sensor=false

JSON for Taj Mahal India is here http://maps.googleapis.com/maps/api/geocode/json?address=Taj%20Mahal%20India&sensor=false

推荐答案

应为

$.each(data.results[0].address_components, function(i,inside)

代替

$.each(data.results.address_components, function(i,inside)

因为要从第一个results组中获取数据.这是 演示

because you are taking data from the first results set. Here is a demo

注意::我不知道是否可以有多个results.如果可以,那么您必须首先遍历results,然后在address_components上对其进行迭代.

Note: I don't know if there can be multiple results. If it can, then you must first iterate over the results and then inside it on address_components.

这篇关于JSON解析与jQuery循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆