我正在使用PHP脚本来生成json数组。 json数组由jquery ajax脚本检索,然后尝试读取它并将其嵌入html表中。但是,由于它会在表中不断生成“未定义”的数据,因此我感到很困惑。我想在ajax成功返回后在表中显示json数组的信息。请帮忙...

JSON数组格式

[{"fullname":"Frank Robsinga","gender":"Male","email":"n\/a","phone":"n\/a","status":"1"}]


JavaScript

<script>
$("#lookup").click(function() {

var key = $("#search").val();

$.ajax({
    type : 'POST',
    url : 'scripts/search-user-script.php',
    data : {
        key : key
    },
    success : function(obj) {

        $("#usersdata").html("");
        for (var i = 0; i < obj.length; i++) {
            var tr = "<tr>";
            var td0 = "<td>" + (i + 1) + "</td>";
            var td1 = "<td>" + obj[i]["fullname"] + "</td>";
            var td2 = "<td>" + obj[i]["gender"] + "</td>";
            var td3 = "<td>" + obj[i]["email"] + "</td>";
            var td4 = "<td>" + obj[i]["phone"] + "</td>";
            var td5 = "<td>" + obj[i]["status"] + "</td></tr>";
            $("#usersdata").append(tr + td0 + td1 + td2 + td3 + td4 + td5);

        }

    }
});
// .ajax
});
</script>


结果截图
javascript - 无法在html表中显示json数组-LMLPHP

最佳答案

var obj = [{
  "fullname": "Frank Robsinga",
  "gender": "Male",
  "email": "n\/a",
  "phone": "n\/a",
  "status": "1"
}]

for (var i = 0; i < obj.length; i++) {
  console.log(obj[i].fullname)
  console.log(obj[i].gender)
  console.log(obj[i].email)
  console.log(obj[i].phone)
  console.log(obj[i].status)
}

<table id='usersdata'></table>





您还必须.[""]一样删除obj[i].status

你的ajax应该看起来像:

$.ajax({
    type : 'POST',
    url : 'scripts/search-user-script.php',
    dataType:'json',
    data : {
        key : key
    },
    success : function(obj) {

        $("#usersdata").html("");
        for (var i = 0; i < obj.length; i++) {
            var tr = "<tr>";
            var td0 = "<td>" + (i + 1) + "</td>";
            var td1 = "<td>" + obj[i].fullname + "</td>";
            var td2 = "<td>" + obj[i].gender + "</td>";
            var td3 = "<td>" + obj[i].email + "</td>";
            var td4 = "<td>" + obj[i].phone + "</td>";
            var td5 = "<td>" + obj[i].status + "</td></tr>";
            $("#usersdata").append(tr + td0 + td1 + td2 + td3 + td4 + td5);

        }

    }
});

关于javascript - 无法在html表中显示json数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37136562/

10-10 09:45