【问题标题】:Rest Api: data shows on console but html table shows undefinedRest Api:数据显示在控制台上,但 html 表显示未定义
【发布时间】:2020-12-27 17:13:27
【问题描述】:

我的帖子数据正在控制台上显示。但是html表显示未定义

下图显示了问题。

我的 Jquery 代码:

$(document).ready(function(){
    //Loading all posts
    var loadposts=function(){
            
            $.ajax({
            
            url:"http://localhost:12091/api/post/",
            crossdomain: true,
            method:"GET",
            complete:function(xmlhttp,status){
                if(xmlhttp.status==200)
                {
                    
                    var data=xmlhttp.responseJSON;
                    $("#msg").html(data[0]);
                    console.log(data[0]);
                    
                    
                        var str='';
                        for (var i = 0; i < data.length; i++) {
                            str += "<tr>";
                            str += "<td>"+data[i].UserId+"</td>";
                            str += "<td>"+data[i].PostId+"</td>";
                            str += "<td>"+data[i].Post1+"</td>";
                            str += "<td><button class='btn btn-danger' onclick=\"deletepost("+data[i].PostId+")\">Delete</button></td>";
                            str += "<td><button class='btn btn-info' onclick=\"editpost()\">Edit</button></td>";
                            str += "</tr>";
                        }
                        $("#show__posts tbody").html(str);
                    
                }
                else
                {
                    $("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
                }
        }
        });
    }
    loadposts();
});

html表格:

<div class="container">
    <p id="msg"></p>
    <table class="table table-striped" border="1" id="show__posts" cellspacing="0" cellpadding="0">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Post Id</th>
                <th>Post</th>
                <th>Delete</th>
                <th>Edit</th>
            </tr>
        </thead>
        <tbody>
            
        </tbody>
        
    </table>
</div>

我做错了什么? 可能无关紧要,但我在后端使用 asp.net web api

【问题讨论】:

    标签: html jquery asp.net rest


    【解决方案1】:

    JavaScript 没有对象的.length 属性。如果你想解决这个问题,你必须改用Object.keys(data).length

    【讨论】:

      猜你喜欢
      • 2012-01-17
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多