如何将JSON转换为数组并在jQuery中循环它?

我正在使用JSON与用户进行通信。 PHP将数组转换为JSON为此forms:

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

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

  

我认为使用数组:

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

而不是这个:

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

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

PHP:

 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 ""; 

这将输出以下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/