javascript - 如何将 JSON 转换为数组并在 jQuery 中对其进行循环?

标签 javascript php jquery arrays json

我正在使用 JSON 与用户通信。 PHP 将数组转换为 JSON 为这种形式:

{"success":"text-to-display","warning":"NONE","notice":"text-to-display","error":"NONE"}

jQuery 显示通知:

function callback (data){
    if(data.notice !== 'NONE'){
        displayNotice(data.notice);
    }
    if(data.success !== 'NONE'){
        displaySuccess(data.success);
    }
    if(data.warning !== 'NONE'){
        displayWarning(data.warning);
    }
    if(data.error !== 'NONE'){
        displayError(data.error);
    }
}

不幸的是,在这个方法中不能显示两个错误或两个通知或两个警告,因为新语句替换旧语句。

<?php
$uwaga['error'] = 'old statement';
$uwaga['error'] = 'new statement';
// display only "new statement"
echo json_encode($uwaga);
?>

我认为使用数组:

<?php
$uwaga = array();
$uwaga[1] = array('type' => 'notice', 'text' => 'old statement');
$uwaga[2] = array('type' => 'notice', 'text' => 'new statement');
// display "new statement" and "old statement"
// generate: {"1":{"type":"notice","text":"old statement"},"2": {"type":"notice","text":"new statement"}}
    echo json_encode($uwaga);
?>

如何在 jQuery 上“翻译”这段 PHP 代码(主要是:如何将 json 对象转换为数组?循环如何使用?如何使用循环?如何引用 $uwaga[$key]['name']$uwaga[$key]['text'])?

foreach ($uwaga as $key => $value) {
switch ($uwaga[$key]['name']) {
    case 'warning':
        displayWarning($uwaga[$key]['text']);
        break;
}}

最佳答案

好吧,假设我们有一个 PHP 数组

PHP:

<?php
$myArray = array(
    "test1"=>array("name"=>"test1name", "value"=>"test1value"),
    "test2"=>array("name"=>"test2name", "value"=>"test2value"),
    "test3"=>array("name"=>"test3name", "value"=>"test3value")
);

// Now make a javascript variable containing echoed JSON
echo "<script type='text/javascript'>var returnedJSON = " . json_encode($myArray) . ";</script>";

这将输出以下 JSON,为您提供一个 javascript 对象:

var returnedJSON = {"test1":{"name":"test1name","value":"test1value"},"test2":{"name":"test2name","value":"test2value"},"test3":{"name":"test3name","value":"test3value"}};

Javascript:

//Once you have the variable from above which can come in various ways (through ajax, jsonp etc) you can iterate over it quite simply in jQuery
$.each(returnedJSON, function (index, value) {
    console.log(index + ": " + value.name);
});

http://api.jquery.com/jquery.each/

演示 http://jsfiddle.net/robschmuecker/HqarE/1/

关于javascript - 如何将 JSON 转换为数组并在 jQuery 中对其进行循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594241/

相关文章:

javascript - 以不同的顺序绑定(bind)参数

javascript - 如何更改 JavaScript 中日期的格式?

javascript - 表单提交上的 Angular 2 错误 TypeError : _co. onSubmit 不是函数

javascript - 通过 HTTP GET 传递多个参数

javascript - 当我使用元素数组时,Jquery element.text() 错误 "is not a function"

javascript - 在 d3 svg 路径中​​查找坐标

PHP 按类型对目录中的文件进行排序

php - 使用 PHP session 并使用 PDO 选择 bool?

php - 使用 jQuery 发布屏幕宽度

jQuery - 从 HTML 中删除 Accordion