在我的PHP脚本中,我正在尝试将我的乘法新闻数组编码为JSON。
我的新闻阵列:
$news[1]["header"] = "First header";
$news[1]["content"] = "First news content";
$news[2]["header"] = "Second header";
$news[2]["content"] = "Second news content";
我使用此函数对此数组进行编码:
json_encode($news);
之后,我将这个JSON数据发送到我的JS脚本中。
var result = JSON.parse(xmlHttp.responseText); // Here is my JSON object
我怎样才能获得,例如我的JavaScript代码中的第一个新闻标题?
感谢您的帮助。我很难用unsontand json语法。
答案 0 :(得分:0)
JSON.parse
创建一个对象,其中属性(键)为1
,2
等。因此,您可以使用result[1].header
或result[1]['header']
访问第一个标头
您还可以通过迭代结果来访问标题:
for (var index in result) {
if (result.hasOwnProperty(index)) {
console.log(result[index].header);
}
}
输出:
First header
Second header
编辑:以下是演示:
var json = '{"1":{"header":"First header","content":"First news content"},"2":{"header":"Second header","content":"Second news content"}}';
var result = JSON.parse(json);
console.log(result[1].header);
for (var index in result) {
if (result.hasOwnProperty(index)) {
console.log(result[index].header);
}
}

答案 1 :(得分:0)
var json = '{"1":{"header":"First header","content":"First news content"},"2":{"header":"Second header","content":"Second news content"}}';
var result = JSON.parse(json);
console.log(result[1].header);
for (var index in result) {
if (result.hasOwnProperty(index)) {
console.log(result[index].header);
}
}