尝试解析json数组时未返回undefined
问题描述:
我转换为json并回显我想使用jquery进行检索的php数组。回显的json的格式如下:尝试解析json数组时未返回undefined
[{"id":"1","title":"Test Event 1","description":"This is the first test event","location":"Acme Hall, Room 101","contact":"John Smith","url":"http:\/\/www.example.com","start":"2016-02-29 13:00:00","end":"2016-02-29 14:00:00"},
{"id":"2","title":"Test Event 2","description":"This is the second test event","location":"Venable Hall, Room 101","contact":"Jane Smith","url":"http:\/\/www.example.com","start":"2016-03-08 09:00:00","end":"2016-03-10 10:45:00"},
{"id":"3","title":"Test Event 3","description":"This is the third test event","location":"Sitterson Hall, Room 200","contact":"Jane Smith","url":"http:\/\/www.example.com","start":"2016-03-18 15:00:00","end":"2016-02-22 16:30:00"}]
当我尝试使用Ajax GET来解析并显示JSON时,会返回'undefined'。我的Ajax代码是:
$.ajax({
type: 'GET',
url: 'get-events.php',
dataType: "json",
cache: false,
success: function (result) {
alert(result[start]);
},
});
UPDATE:
感谢您的答复。我终于得到它使用排序
for (var key in result) {
if (result.hasOwnProperty(key)) {
result[key].id
}
}
答
你的结果是一个表,所以你必须指定索引:结果[指数]
然后,JSON是一个十“关键”:“值”}格式,其中键是一个字符串。在你的代码中你使用了start,这是一个未定义的变量。
所以,你应该尝试:
alert(result[0]["start"]);
答
看来你不使用结果值的正确方法。结果是一个对象数组。如果你想访问第一个元素的起始值,你必须使用result[0].start
。
要访问所有值,您应该使用for循环遍历数组。
for (var i = 0; i < result.lenght; i++) {
// result[i].start
}
什么是变量'start'? – epascarello