如何循环返回的JSON数据


How to loop through returned JSON data

我目前正在一个自定义Joomla组件中创建一个JSON表单,该组件调用一个函数来获取一个邮政编码数组,然后将其返回到视图。然后,我想循环浏览所有返回的邮政编码,以便显示它们。我似乎无法让jQuery.each循环正确地循环返回的值。这是我的代码:

视图:

jQuery.each(data.postcode, function() {
        html += "<span class='btn posctodeInv'>" + v + "</span>";                       
    });

控制器:

$club_id = $_POST['club_id'];
$model = $this->getModel('postcodes');
$postcodes = $model->getClubPostcodes($club_id);
header('Content-Type: application/json');
echo json_encode($postcodes);

型号:

public function getClubPostcodes($club_id) {
        $query = "SELECT postcode FROM #__postcodes_to_club WHERE club_id = '" . (int)$club_id . "'";
        $this->_db->setQuery($query);
        $result = $this->_db->loadAssocList();
        return $result;
    }

以及Firebug控制台中显示的返回json:

[{"postcode":"cr4"},{"postcode":"cr5"},{"postcode":"cr6"}]

有人能解释为什么我的循环会出现错误吗?谢谢

尝试

jQuery.each(data, function(index, val) {
    html += "<span class='btn posctodeInv'>" + val.postcode + "</span>";                       
});

Try,需要index和val参数在jQuery.each 中循环

jQuery.each(data, function(index, val) {
        html += "<span class='btn posctodeInv'>" + val.postcode + "</span>";                       
    });
var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
  var obj = $.parseJSON(jsonp);
  $.each(obj, function() {
      alert( this['Lang']);
  });

我认为你的问题和上面类似。尝试以上方法