gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:40:01 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com