0

问题是我已经可以通过firebug看到我的json的值但是问题是将它附加到我的表中我尝试将我的json_encode从echojson_encode(array('red'=>$red, 'blue'=>$blue));更改json_encode($blue);为查看我的ajax是否真的有效然后json_encode($blue);我将其更改toAppend += '<tr><td>'+data.red[i]['warrior_name']+'</td><td>Name</td><td>'+data.blue[i]['warrior_name']+'</td></tr>';toAppend += '<tr><td>'+data[i]['warrior_name']+'</td></tr>';然后它完美显示我的桌子,但只有蓝色阵列,我想要蓝色和红色阵列。所以我想知道出了什么问题或者我遗漏了什么?

这是我的 PHP 代码:

   //get blue_team attributes
$blue = array();

$blue_result = $db->dataWarrior($battle_id,$blue_name);

foreach($blue_result as $warrior){
    $blue[] = $warrior;
}

//get red_team attributes
$red = array();

$red_result = $db->dataWarrior($battle_id,$red_name);

foreach($red_result as $warrior){
    $red[] = $warrior;
}

    echo json_encode(array('red'=>$red, 'blue'=>$blue));

这是我的ajax代码:

$.ajax({
                url: "battle_review.php",
                type: "post",
                datatype: "json",
                data: { 
                    bname: blue_name,
                    btype: blue_type,
                    rname: red_name,
                    rtype: red_type },
                success: function(data){
                    var toAppend = '';
                    if(typeof data === "object"){
                        for(var i=0;i<data.length;i++){
                            toAppend += '<tbody>';
                            toAppend += '<tr><td>'+data.red[i]['warrior_name']+'</td><td>Name</td><td>'+data.blue[i]['warrior_name']+'</td></tr>';

                            toAppend += '</tbody>';
                        }
                        $("#battledata").append(toAppend);
                    }
                }
            });
4

1 回答 1

1

您的输出结构对于对其进行适当的迭代非常糟糕。但是,假设red并且blue始终具有相同的元素计数,您可以这样做:

$.ajax({
    url: "battle_review.php",
    type: "POST", // uppercase
    dataType: "json", // uppercase T
    data: {
        bname: blue_name,
        btype: blue_type,
        rname: red_name,
        rtype: red_type
    },
    success: function(data) {
        var toAppend = '';
        for(var i = 0; i < data.red.length; i++) {
            toAppend += '<tbody>';
            toAppend += '<tr><td>' + data.red[i].warrior_name. + '</td><td>Name</td><td>' + data.blue[i].warrior_name + '</td></tr>';

            toAppend += '</tbody>';
        }
        $("#battledata").append(toAppend);
    }
});

像这样的数组会更干净:

[{"red": ..., "blue": ...},
 {"red": ..., "blue": ...},
]

然后您可以简单地对其进行迭代并访问元素的redblue属性:

$.each(data, function(i, row) {
    // row.red
    // row.blue
});
于 2012-09-16T14:35:13.503 回答