0

I'm trying to create a table to show persisted highscores coming from a MySQL database. Though I have the data coming into the code (JSON format) I'm having trouble displaying it in a presentable way. I'm trying to append a table to the body with the highscore data. The number of rows will depend on how much data there is, but the number of columns will always be two.

$.ajax({
    url : '../server.php',
    type : 'GET',
    success : function(response) {
        var toAppend = '<table style="position: fixed; top:200px; left: 200px;" id="highscores">';
        var jsonObject = eval(response);
        var highscores = "";
        for ( i = 0; i < jsonObject.length && i < 10; i++) {
            highscores += jsonObject[i].Name + " " + jsonObject[i].Score + "\n";
            toAppend += "<tr>";
            toAppend += jsonObject[i].Name;
            toAppend += "</tr><tr>";
            toAppend += jsonObject[i].Score;
            toAppend += "</tr>";
        }
        toAppend += "</table>";
        $('body').append(toAppend);
        alert(highscores);
    },

    error : function() {
        alert("fail");
    }
});

This is my code to receive the json data from the server which has taken the MySQL data and converted it into JSON. I have alerts in the code for debugging but this is not how I want to display the data. I want a new row on the table for every score and each row will have two columns. One for name and one for score.

4

1 回答 1

2

您为每个值添加行,而不是为每个对象添加一行,然后在其中添加单元格。

更像这样的东西:

var toAppend = $('<table style="position: fixed; top:200px; left: 200px;" id="highscores"></table>');
var jsonObject = eval(response);

for ( i = 0; i < jsonObject.length && i < 10; i++) {
  var newRow = $('<tr></tr>');
  $('<td></td>').text(jsonObject[i].Name).appendTo(newRow);
  $('<td></td>').text(jsonObject[i].Score).appendTo(newRow);
  newRow.appendTo(toAppend);
}

$('body').append(toAppend);
于 2013-08-26T19:20:44.753 回答