My Json objects are inside a external file named abc.json in my js file I am calling it. I have a html markup like this
<li class="" data-flight-name="kingfisher" data-flight-id="E6-184"></li>
<li class="" data-flight-name="indigo" data-flight-id="E6-185"></li>
My requirement is when ever i click on that LI pass this data-flight-name and data-flight-id while fetching the information through JSON but while fetching I am not getting proper data.
My Json File structure is
{
"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"}}
]
}
}
Used jquery for fetching information is
$("#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]);
});
});
});
}
});
Please help to understand why I am not able to get the all values.
You have the syntax for
.delegate()a bit mixed up, it goes:$(<root element>).delegate(<selector>, <event>, <callback>). When you try to access your JSON object you append a[0]onto the end which is unnecessary (data.flightInfo[dataflightname][0]should bedata.flightInfo[dataflightname]):Here is a demo: http://jsfiddle.net/HscZX/
Notice I cached the
$(this)selector in the$thisvariable since it was being used so many times which should improve performance. Also I changed out the$.each()loop for afor (var i = 0, len = data.length; i < len; i++) {}beacuse the later performs much faster. Check-out this jsperf to see the difference in performance: http://jsperf.com/for-in-tests/4