json decode with jQuery using codeigniter


json decode with jQuery using codeigniter

我需要知道如何使用 jquery 附加我的数组。 以下是我的代码

代码点火器中的模型

public function getranking(){
    $this->db->select('*')->from('tour_ranking');
    $this->db->join('teams','teams.team_id = tour_ranking.team_id');
    $query = $this->db->get();
    return $query->result();

}   

这给出了这样的输出

   [
{
"Rank_Id": "1",
"Tour_id": "1",
"Team_id": "1",
"match_palyed": "1",
"Points": "100",
"Rating": "1",
"match_loss": "0",
"match_win": "1",
"is_display": "1",
"team_id": "1",
"team_name": "pakistan",
"is_active": "0",
"short_name": "PK",
"image_ex": "Pk.png"
}
]

我正在使用的jquery是

$.getJSON('http://localhost/main/ranking/',function(data){ count=0;
    $('#rank-table').append('<tr class="rankingTr"><td class="rankingTd" id="rank-teamName">'+data'team_name'+' </td><td class="rankingTd" id="rank-matchplayed">'+data.match_palyed+'</td><td class="rankingTd" id="rank-points">'+data.Points+'</td><td class="rankingTd" id="rank-rating">'+data.Rating+'</td></tr>')
 });

我可以在我的控制台命中中看到结果,但是当我附加它时,它给了我未定义

因为你的输出是对象数组,所以你需要使用 $.each(),作为:

$.getJSON('http://localhost/main/ranking/',function(data){ 
    count=0;
    $.each(data, function(i, val) {
        //do your append here using val.points, val.short_name, etc
        console.log(val.short_name);
    });
});

您接收的是数组而不是对象。 []{}分别是数组和对象,请确保不要与它的两个关系混淆。

您可以通过将数据从数组转换为对象来修复它。

$.getJSON('http://localhost/main/ranking/',function(data){ 
    data = data[0];  // just adding this line and you will get the object from first item in array.
    count=0;
    $('#rank-table').append('<tr class="rankingTr"><td class="rankingTd" id="rank-teamName">'+data'team_name'+' </td><td class="rankingTd" id="rank-matchplayed">'+data.match_palyed+'</td><td class="rankingTd" id="rank-points">'+data.Points+'</td><td class="rankingTd" id="rank-rating">'+data.Rating+'</td></tr>')
 });