【问题标题】:JSON and PHP encode multiply arrayJSON 和 PHP 编码乘法数组
【发布时间】:2014-09-21 12:35:25
【问题描述】:

在我的 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);

之后,我在我的 JS 脚本中发送这个 JSON 数据。

var result = JSON.parse(xmlHttp.responseText); // Here is my JSON object

如何获取,例如我的 JavaScript 代码中的第一个新闻标题?

感谢您的帮助。我真的很难理解 json 语法。

【问题讨论】:

    标签: javascript html json parsing encode


    【解决方案1】:

    JSON.parse 创建一个对象,其中属性(键)为12 等。因此您可以使用result[1].headerresult[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);
        }
    }

    【讨论】:

    • result[1].header 什么都不返回
    • resultxmlHttp.responseText 的值是多少?在我的答案中添加了一个演示脚本。
    • 很奇怪。您的演示工作正确。我的 .responseText 什么都不返回。
    • 是的。我只是没有在我的 php 脚本中编写 json_encode。现在它工作正常。非常感谢!
    【解决方案2】:

    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);
        }
    }

    【讨论】:

    • 请添加一些解释。
    猜你喜欢
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多