Hi everyone I am trying to read some json and do 2 things. Insert some of the json data into a UL. Second thing is create a function that can be called from a anchor tag and displays the other data.Let me try explain with my code.
My json looks like this
[{lakeName:"Lake 1",lakeCode:"111",Readings[["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5],]}{lakeName:"Lake 2",lakeCode:"222",Readings[["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5],]}]
I am trying to populate my list like this
$(document).ready(function () {
$.ajax({
url: "http://theaboveJSONisreturnedFromMyUrl",
method: 'GET',
dataType: 'json',
success: onDataReceived
});
var data = [];
function onDataReceived(series) {
data = [series];
$(data).each(function (i, data) {
开发者_JAVA百科 $('#myList').append("<li>" + "<a href=\"javascript:GetLake(" + data.lakeCode + ");\">" + data.lakeName + "</a></li>");
});
}
});
function GetLake(lake) {
alert('some how get the readings for the clicked lake code e.g. lakeCode 111 and display them here ["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5] );
}
Now I see values in data however I cant seem to access the through e.g. data.lakeCode
What have I done wrong?
Any help would be great!!!
There are several syntax errors in your JSON. It should look like this:
[{lakeName:"Lake 1",lakeCode:"111",Readings:[["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5]]},{lakeName:"Lake 2",lakeCode:"222",Readings:[["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5]]}]
Some :
and ,
were missing, unnecessary ,
in between and an unneeded ]
was at the end.
when your are not sure of your JSON's syntax just check it with that: http://www.jsonlint.com/
To be valid, your JSON needs the following changes (you can check always validity with JSONLint here):
- Commas between objects in the main array
- No trailing commands in the
Readings
arrays - Double quotes around member names
:
betweenReadings
and its value
Over all it should look like this:
[{"lakeName":"Lake 1","lakeCode":"111","Readings":[["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5] ]},{"lakeName":"Lake 2","lakeCode":"222","Readings":[["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5] ]}]
//compared to your current version:
[{ lakeName :"Lake 1", lakeCode :"111", Readings [["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5],]} { lakeName :"Lake 2", lakeCode :"222", Readings [["24-Oct-10",12.5],["24-Oct-10",10.5],["24-Oct-10",15.5],]}]
Also, you should use $.each()
here instead , like this:
$.each(data, function () {
$('#myList').append("<li>" + "<a href=\"javascript:GetLake(" + this.lakeCode + ");\">" + this.lakeName + "</a></li>");
});
Or a bit better, use DOM methods like this:
$.each(data, function () {
$('<a />', { href: '#', click: function() { GetLake(this.lakeCode); } })
.wrap('<li />').parent().appendTo('#myList');
});
精彩评论