我正在使用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);
?>
&#34;翻译&#34;这个关于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;
}}
答案 0 :(得分:2)
好吧,假设我们有一个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);
});
答案 1 :(得分:1)
而不是:
$uwaga = array();
$uwaga[1] = array('type' => 'notice', 'text' => 'old statement');
$uwaga[2] = array('type' => 'notice', 'text' => 'new statement');
这样做,没有索引:
$uwaga = array();
$uwaga[] = array('type' => 'notice', 'text' => 'old statement');
$uwaga[] = array('type' => 'notice', 'text' => 'new statement');
这将在数组的末尾为它们分配索引(从零而不是一个)。
然后采取所有这些:
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);
}
...并将其包装在一个jQuery的each()
块中,如Rob推荐的那样。然后它将成为(假设数据在json.messages
):
$.each(json.messages, function (index, 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);
}
});