0

我目前正在自定义 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"}]

谁能解释为什么我的循环会引发错误?谢谢!

4

3 回答 3

2

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

jQuery.each(data, function(index, val) {
        html += "<span class='btn posctodeInv'>" + val.postcode + "</span>";                       
    });
于 2013-04-10T09:39:48.600 回答
2

尝试

jQuery.each(data, function(index, val) {
    html += "<span class='btn posctodeInv'>" + val.postcode + "</span>";                       
});
于 2013-04-10T09:40:40.007 回答
0
var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
  var obj = $.parseJSON(jsonp);
  $.each(obj, function() {
      alert( this['Lang']);
  });

我认为您的问题与上述类似。试试上面的方法

于 2013-04-10T10:15:25.630 回答