如何使用jquery从JSON对象获取信息

时间:2011-12-12 07:12:43

标签: jquery html json jsonp

我的Json对象位于我调用它的js文件中名为abc.json的外部文件中。我有像这样的HTML标记

<li class="" data-flight-name="kingfisher" data-flight-id="E6-184"></li>
<li class="" data-flight-name="indigo" data-flight-id="E6-185"></li>

我的要求是,当我点击该LI时,通过JSON获取信息时通过此数据 - 航班名称和数据 - 航班ID,但在获取时我没有获得正确的数据。

我的Json文件结构是

{
  "flightInfo" :{
    "indigo": [
          {"E-184" : {"flightName": "Indigo", "duration": "1h:0m", "baseFare": 1753, "travelTime": "11:13 - 12:13"}},
          {"E-185" : {"flightName": "Indigo", "duration": "1h:0m", "baseFare": 1753, "travelTime": "11:13 - 12:13"}},
          {"E-186" : {"flightName": "Indigo", "duration": "2h:30m", "baseFare": 8000, "travelTime": "11:13 - 16:13"}},
          {"E-187" : {"flightName": "Indigo", "duration": "6h:30m", "baseFare": 6000, "travelTime": "11:13 - 16:13"}},
          {"E-189" : {"flightName": "Indigo", "duration": "5h:0m", "baseFare": 9907, "travelTime": "11:13 - 16:13"}}
      ],

    "kingfisher": [
          {"E-184" : {"flightName": "KF RED", "duration": "1h:0m", "baseFare": 2819, "travelTime": "10:13 - 11:13"}},
          {"E-184" : {"flightName": "KF RED", "duration": "1h:0m", "baseFare": 2819, "travelTime": "11:13 - 16:13"}},
          {"E-184" : {"flightName": "KF RED", "duration": "2h:30m", "baseFare": 18000, "travelTime": "11:13 - 16:13"}},
          {"E-184" : {"flightName": "KF RED", "duration": "6h:30m", "baseFare": 16000, "travelTime": "11:13 - 16:13"}}
      ]
  }
}

使用jquery获取信息是

$("#list li").delegate("", "click", function(e){
        var dataflightname = $(this).attr('data-flight-name'),
            dataflightid = $(this).attr('data-flight-id');
//            console.log(dataflightname);
//            console.log(dataflightid);
        if($(this).siblings().hasClass('selected')){
          $(this).siblings().removeClass('selected');
          $(this).addClass('selected');
          // Featcing Flights Information
          $.getJSON("javascript/abc.json",function(data){

            $(data.flightInfo[dataflightname][0]).each(function(key, items) {
              $(data.flightInfo[dataflightname][key]).each(function(key, items) {
              //Reading name tag value
              //here i am not getting proper value
              console.log(data.flightInfo[dataflightname][0][items]);
              });
            });
          });
        }
      });

请帮助理解为什么我无法获得所有值。

4 个答案:

答案 0 :(得分:2)

.delegate()的语法有点混淆,它是:$(<root element>).delegate(<selector>, <event>, <callback>)。当您尝试访问JSON对象时,将[0]附加到末尾,这是不必要的(data.flightInfo[dataflightname][0]应为data.flightInfo[dataflightname]):

$("#list").delegate("li", "click", function(e){
    var $this          = $(this),
        dataflightname = $this.attr('data-flight-name'),
        dataflightid   = $this.attr('data-flight-id');

    if($this.siblings().hasClass('selected')){
      $this.siblings().removeClass('selected');
      $this.addClass('selected');

      // Featcing Flights Information
      $.getJSON("javascript/abc.json",function(data){
        for (var i = 0, len = data.flightInfo[dataflightname].length; i < len; i++) {
            console.log(data.flightInfo[dataflightname][i]);
            //output will be (for the first index): {"E-184" : {"flightName": "Indigo", "duration": "1h:0m", "baseFare": 1753, "travelTime": "11:13 - 12:13"}}
        }
      });
    }
  });

以下是演示:http://jsfiddle.net/HscZX/

注意我在$(this)变量中缓存了$this选择器,因为它被多次使用会提高性能。此外,我更改了$.each()循环for (var i = 0, len = data.length; i < len; i++) {},因为后来执行更快。检查此jsperf以查看性能差异:http://jsperf.com/for-in-tests/4

答案 1 :(得分:1)

编辑您的javascript,如下所示:

$("#list li").delegate("", "click", function(e){
    var dataflightname = $(this).attr('data-flight-name'),
    dataflightid = $(this).attr('data-flight-id');
    if($(this).siblings().hasClass('selected')){
        $(this).siblings().removeClass('selected');
        $(this).addClass('selected');
        // Featcing Flights Information
        $.getJSON("/cygnet-ng/test.json",function(data){
            $(data.flightInfo[dataflightname]).each(function(key, items) {
                $(items).each(function(key1, items1) {
                //Reading name tag value 
                //here i am not getting proper value 
                    for(n in items1){
                           console.log(items1[n].flightName);
                           console.log(items1[n].duration);
                           console.log(items1[n].baseFare);
                           console.log(items1[n].travelTime);
                    }    
                });
            });
        });
    }
});

这将迭代json数据。

答案 2 :(得分:0)

首先:改变你的数据结构:

{
    "flightInfo": {
        "indigo": {
            "E-184": {
                "flightName": "Indigo",
                "duration": "1h:0m",
                "baseFare": 1753,
                "travelTime": "11:13 - 12:13"
            },
            "E-185": {
                "flightName": "Indigo",
                "duration": "1h:0m",
                "baseFare": 1753,
                "travelTime": "11:13 - 12:13"
            },
            "E-186": {
                "flightName": "Indigo",
                "duration": "2h:30m",
                "baseFare": 8000,
                "travelTime": "11:13 - 16:13"
            },
            "E-187": {
                "flightName": "Indigo",
                "duration": "6h:30m",
                "baseFare": 6000,
                "travelTime": "11:13 - 16:13"
            },
            "E-189": {
                "flightName": "Indigo",
                "duration": "5h:0m",
                "baseFare": 9907,
                "travelTime": "11:13 - 16:13"
            }
        },

        "kingfisher": {
            "E-184": {
                "flightName": "KF RE}D",
                "duration": "1h:0m",
                "baseFare": 2819,
                "travelTime": "10:13 - 11:13"
            },
            "E-184": {
                "flightName": "KF RED",
                "duration": "1h:0m",
                "baseFare": 2819,
                "travelTime": "11:13 - 16:13"
            },
            "E-184": {
                "flightName": "KF RED",
                "duration": "2h:30m",
                "baseFare": 18000,
                "travelTime": "11:13 - 16:13"
            },
            "E-184": {
                "flightName": "KF RED",
                "duration": "6h:30m",
                "baseFare": 16000,
                "travelTime": "11:13 - 16:13"
            }
        }
    }
}

然后,你想要的是:

data.flightInfo[dataflightname][dataflightid];

$("#list li").click(function (e) {
    var dataflightname = $(this).attr('data-flight-name'),
        dataflightid = $(this).attr('data-flight-id');
    if ($(this).siblings().hasClass('selected')) {
        $(this).siblings().removeClass('selected');
        $(this).addClass('selected');
        // Featcing Flights Information
        $.getJSON("javascript/abc.json", function (data) {
            console.log(data.flightInfo[dataflightname][dataflightid]);
        });
    }
});

答案 3 :(得分:0)

让我们分析以下代码部分

data.flightInfo[dataflightname][0]

使用此行,您将获得{"E-184" : {"flightName": "Indigo", "duration": "1h:0m", "baseFare": 1753, "travelTime": "11:13 - 12:13"}}“indigo”,这只是此dataflightname的第一个条目。

接下来,您将尝试循环此条目的所有键。只有一个:"E-184"

以下代码行

data.flightInfo[dataflightname][key]

将是未定义的data.flightInfo["indigo"]["E-184"]

编辑:如果你描述了你想要实现的目标,那将会有所帮助

EDIT2:我认为你的某个地方有错字...来自data-flight-id属性的E6-184与你JSON中的任何东西都不匹配