大家好我想读一些json并做两件事。 将一些json数据插入UL。第二件事是创建一个可以从锚标签调用并显示其他数据的函数。让我尝试用我的代码解释。
我的json看起来像这样
[{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],]}]
我正在尝试像这样填充我的列表
$(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) {
$('#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] );
}
现在我看到数据中的值但是我似乎无法访问通过例如data.lakeCode
我做错了什么?
任何帮助都会很棒!!!
答案 0 :(得分:0)
您的JSON中存在多个语法错误。它应该是这样的:
[{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]]}]
某些:
和,
丢失,中间不必要,
,最后不需要]
。
答案 1 :(得分:0)
当你不确定你的JSON语法时,只需检查它: http://www.jsonlint.com/
答案 2 :(得分:0)
要生效,您的JSON需要进行以下更改(you can check always validity with JSONLint here):
Readings
数组:
介于Readings
及其值之间
总而言之,它应该是这样的:
[{"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],]}]
此外,您应该在此使用$.each()
,如下所示:
$.each(data, function () {
$('#myList').append("<li>" + "<a href=\"javascript:GetLake(" + this.lakeCode + ");\">" + this.lakeName + "</a></li>");
});
或者更好一点,使用这样的DOM方法:
$.each(data, function () {
$('<a />', { href: '#', click: function() { GetLake(this.lakeCode); } })
.wrap('<li />').parent().appendTo('#myList');
});