从外部json文件获取对象数组,并将其存储为JavaScript中的数组 [英] Get an array of objects from an external json file and store as an array in javascript
本文介绍了从外部json文件获取对象数组,并将其存储为JavaScript中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将JavaScript数组分配给EXTERNAL json文件中的对象数组?
How do I assign a javascript array to that of an array of objects from an EXTERNAL json file?
这就是我尝试过的.
JavaScript代码段
var i = 0;
var testjson = $.getJSON('/TestJSON');
jsonObj = JSON.parse(testjson);
$("#testJSONBtn").click(function () {
while (i <= jsonObj.events.length) {
$("#JSONOutput").append(jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>")
i += 1;
}
});
JSON文件内容
{
"events":
[
{"title":"Okmulgee Public Schools Starts 3rd Quarter" , "date":"1-2-2013" , "explanation":"Okmulgee Public Schools begins its third quarter."}
{"title":"Okmulgee Public Schools-Closed in Observance of Martin Luther King Jr. Holiday" , "date":"1-21-2013" , "explanation":"The Okmulgee Public Schools will be closed in observance of the Martin Luther King Jr. holiday."}
{"title":"Okmulgee Public Schools County Professional Day" , "date":"2-1-2013" , "explanation":"Okmulgee Public Schools County Professional Day is today."}
]
}
我在做什么错了?
推荐答案
AJAX函数没有数据返回值,它们只是返回一个AJAX对象.
AJAX functions do not have data return values, they just return an AJAX object.
您需要使用回调.
尝试一下:
$.getJSON('/TestJSON', function(jsonObj){
$("#testJSONBtn").click(function () {
for(var i = 0; i < jsonObj.events.length; ++i) {
$("#JSONOutput").append(jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>")
}
});
});
更好:
var btn = $("#testJSONBtn"); //cache the element
var output = $("#JSONOutput"); // ^^^
$.getJSON('/TestJSON', function(jsonObj){
btn.click(function () {
var val = "";
for(var i = 0; i < jsonObj.events.length; ++i) {
val += jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>";
}
output.append(val);
});
});
侧面:
Side point:
我不知道它是否是故意的,但是在您的OP中,JSON文件看起来不合法,您缺少逗号. (
I don't know if it was on purpose or not, but in your OP the JSON file does not look legal, you are missing commas. (source)
这篇关于从外部json文件获取对象数组,并将其存储为JavaScript中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文