【问题标题】:Returning JSON response and reconstructing HTML table through jQuery通过 jQuery 返回 JSON 响应并重建 HTML 表
【发布时间】:2017-04-04 10:01:19
【问题描述】:

我有一个 .NET 控制器操作,它基本上在对服务器进行 POST 调用后返回 JSON 响应,如下所示:

 responseDetails.Add(new ActiveSubsPayPal
                        {
                            ProfileID = item.ProfileId,
                            Status = profileType,
                            LastTimePaid = DateTime.Now,
                            NextTimePayment = DateTime.Now,
                            BillingCycle = subType,
                            TotalCyclesCompleted = 2,
                            TotalAmountPaid = 40.0d
                        });

如您所见,响应详细信息是一个包含这些属性的列表。列表中可以有 0、1 或 50 条记录...现在我要做的就是将其转换为 JSON,如下所示:

return  new JavaScriptSerializer().Serialize(responseDetails);


[{"ProfileID":"123","Status":"Not active profile","LastTimePaid":"2016-12-18T21:46:27Z","NextTimePayment":null,"BillingCycle":"Each year","TotalCyclesCompleted":"1","TotalAmountPaid":"180.00"}]

现在是 HTML/jQuery 部分:

 $(".scanSubs").click(function () {
        $.post("/Administrator/GetUserSubs", { uid: $(this).closest('tr').find('.idrowSubs').attr("value") })
        .done(function (response) {

           // reconstruct the HTML table here and inject recontructed HTML => JSON into the DOM

        });
    });

 <table class="table table-striped" id="tableSubs">
               <thead>
                   <tr>
                   <th>PROFILE ID</th>

                   <th>Status</th>
                   <th>Last Time Paid</th>
                   <th>Next Payment</th>
                   <th>Billing Cycles</th>
                    <th>Total Billing Cycles</th>
                       <th>Total Amount Paid</th>
                   </tr>

               </thead>
                <tbody>

                   <tr>
                       <td><b>123</b></td>


                       <td>Active</td>


                       <td>12.12.2012</td>


                       <td>12.12.2012</td>


                       <td>4 Weeks</td>


                       <td>12</td>


                       <td>$122.23</td>
                   </tr>

                </tbody>
            </table>

我现在如何才能真正将 JSON 重构为 HTML 并注入到浏览器中以便我可以看到结果?有人可以帮帮我吗?

【问题讨论】:

  • P.S.伙计们,JSON 数组中的每条记录都应该匹配表本身中的 1 个表行,这最让我感到困惑......
  • 返回表体的部分视图会更容易,但是如果你想返回json,response是一个数组,所以你只需要遍历数组中的每个项目并访问其属性以生成您的 html。
  • @StephenMuecke 你能告诉我怎么做吗?顺便提一句。如果我返回了部分视图,如果在页面加载时最初没有设置,我将如何实际填充表的数据源? =D
  • 您现在有几个答案(虽然不是很好)。在视图中创建一个模板(隐藏)并克隆它并设置值/文本或元素
  • @StephenMuecke 好的,我想我理解你。顺便提一句。我可以这样做吗...我为最初为空的 viewbag.results 设置表的数据源,然后当触发操作时,我只需将此 viewbag 的数据源设置为新列表并返回部分视图?然后简单地更新视图?

标签: javascript jquery asp.net json asp.net-mvc


【解决方案1】:

您可以使用占位符替换html,查看您的html唯一行需要多个所以制作一个行模板。

var template = "
    <tr>
       <td><b>{{ProfileID}}</b></td>
       <td>{{Status}}</td>
       <td>{{NextTimePayment}}</td>
       <td>{{LastTimePaid}}</td>
       <td>{{BillingCycle}}</td>
       <td>{{TotalCyclesCompleted}}</td>
       <td>{{TotalAmountPaid}}</td>
    </tr>"

将剩余的 HTML 放入 html 文件中

<table class="table table-striped" id="tableSubs">
               <thead>
                   <tr>
                   <th>PROFILE ID</th>

                   <th>Status</th>
                   <th>Last Time Paid</th>
                   <th>Next Payment</th>
                   <th>Billing Cycles</th>
                    <th>Total Billing Cycles</th>
                       <th>Total Amount Paid</th>
                   </tr>

               </thead>
                <tbody id="DynamicResponse">
                </tbody>
            </table>

jQUery 代码使用这个

    $.each({"ProfileID":"123","Status":"Not active profile","LastTimePaid":"2016-12-18T21:46:27Z","NextTimePayment":null,"BillingCycle":"Each year","TotalCyclesCompleted":"1","TotalAmountPaid":"180.00"}, function( k, v ) {
     template = template.replace("{{"+k+"}}",v);

    });
 $("#DynamicResponse").append(template);

【讨论】:

    【解决方案2】:

    请使用 $.each(response, function (idx, obj) {} 遍历 JSON 中的每条记录并创建如下所示的 html

     var tableHtml = "<table class="table table-striped" id="tableSubs"><thead><tr><th>PROFILE ID</th><th>Status</th><th>Last Time Paid</th><th>Next Payment</th><th>Billing Cycles</th><th>Total Billing Cycles</th><th>Total Amount Paid</th></tr></thead><tbody>";
                            $.each(data, function (idx, obj) {
                                tableHtml += "<tr>";
                                tableHtml += "<td>" + obj.ProfileID + "</td>";
                                tableHtml += "<td>" + obj.Status + "</td>";
                                tableHtml += "<td>" + obj.LastTimePaid + "</td>";
                                tableHtml += "<td>" + obj.NextTimePayment + "</td>";
                                tableHtml += "<td>" + obj.BillingCycle + "</td>";
                                tableHtml += "<td>" + obj.TotalCyclesCompleted + "</td>";
                                tableHtml += "<td>" + obj.TotalAmountPaid + "</td>";
                                tableHtml += "</tr>";
                            });
                            tableHtml += "</tbody></table>";
                            $("#TABLEID").html(tableHtml);
    

    查看示例数据

     var tableHtml = "<table class='table table-striped' ><thead><tr><th>PROFILE ID</th><th>Status</th><th>Last Time Paid</th><th>Next Payment</th><th>Billing Cycles</th><th>Total Billing Cycles</th><th>Total Amount Paid</th></tr></thead><tbody>";
                $.each([{"ProfileID":"123","Status":"Not active profile","LastTimePaid":"2016-12-18T21:46:27Z","NextTimePayment":null,"BillingCycle":"Each year","TotalCyclesCompleted":"1","TotalAmountPaid":"180.00"}], function (idx, obj) {
                    tableHtml += "<tr>";
                    tableHtml += "<td>" + obj.ProfileID + "</td>";
                    tableHtml += "<td>" + obj.Status + "</td>";
                    tableHtml += "<td>" + obj.LastTimePaid + "</td>";
                    tableHtml += "<td>" + obj.NextTimePayment + "</td>";
                    tableHtml += "<td>" + obj.BillingCycle + "</td>";
                    tableHtml += "<td>" + obj.TotalCyclesCompleted + "</td>";
                    tableHtml += "<td>" + obj.TotalAmountPaid + "</td>";
                    tableHtml += "</tr>";
                });
                tableHtml += "</tbody></table>";
                $("#TABLEID").html(tableHtml);
    

    【讨论】:

    • Ratsheesh 它在这里说:未捕获的类型错误:无法使用 'in' 运算符在 [{"ProfileID":"12345678","Status":"Not active profile"," 中搜索 'length' LastTimePaid":"2017-03-30T21:34:21Z","NextTimePayment":null,"BillingCycle":"Each month","TotalCyclesCompleted":"4","TotalAmountPaid":"119.96"}] 在 isArrayLike : (
    • 确保您的响应有数据并且是有效的 JSON 使用 .JSON.parse(data)
    【解决方案3】:

    要实现这一点,您只需遍历从 AJAX 请求返回的 response 数组,以及一些简单的日期格式。试试这个:

    var response = [{
      "ProfileID": "123",
      "Status": "Not active profile",
      "LastTimePaid": "2016-12-18T21:46:27Z",
      "NextTimePayment": null,
      "BillingCycle": "Each year",
      "TotalCyclesCompleted": "1",
      "TotalAmountPaid": "180.00"
    },{
      "ProfileID": "456",
      "Status": "Not active profile",
      "LastTimePaid": "2017-12-18T21:46:27Z",
      "NextTimePayment": null,
      "BillingCycle": "Each year",
      "TotalCyclesCompleted": "2",
      "TotalAmountPaid": "290.00"
    }]
    
    function formatDate(dateString) {
      if (!dateString)
        return '';
        
      var d = new Date(dateString);
      return ('00' + d.getDate()).slice(-2) + '.' + ('00' + (d.getMonth() + 1)).slice(-2) + '.' + d.getFullYear()
    }
    
    // in the done() handler...
    var html = '';
    response.forEach(function(obj) { 
       html += '<tr>';
       html += '<td>' + obj.ProfileID + '</td>';
       html += '<td>' + obj.Status + '</td>';
       html += '<td>' + formatDate(obj.LastTimePaid) + '</td>';
       html += '<td>' + formatDate(obj.NextTimePayment) + '</td>';
       html += '<td>' + obj.BillingCycle + '</td>';
       html += '<td>' + obj.TotalCyclesCompleted + '</td>';
       html += '<td>$' + obj.TotalAmountPaid + '</td>';
       html += '</tr>';   
    });
    
    $('#tableSubs').append(html);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table table-striped" id="tableSubs">
      <thead>
        <tr>
          <th>PROFILE ID</th>
          <th>Status</th>
          <th>Last Time Paid</th>
          <th>Next Payment</th>
          <th>Billing Cycles</th>
          <th>Total Billing Cycles</th>
          <th>Total Amount Paid</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><b>123</b></td>
          <td>Active</td>
          <td>12.12.2012</td>
          <td>12.12.2012</td>
          <td>4 Weeks</td>
          <td>12</td>
          <td>$122.23</td>
        </tr>
      </tbody>
    </table>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多