首页 > 解决方案 > 如何使用ajax(Get Method)在html页面(客户端)中显示来自node.js服务器的json数据?

问题描述

我正在使用节点 js 服务器,来自这个 url:http://localhost:5000/listproducts 我有以下数据:

[{"Id":1,"Name":"新产品","Description":"P1 desc","Quantity":1},{"Id":2,"Name":"Product2","Description ":"p2 desc","数量":7}]

我想使用 ajax 在 html 页面中显示数据。

我已经在我的 html 页面中尝试过这个:

$('#display').click(function() {
      $.ajax({
          type: 'GET',
          url: 'http://localhost:5000/listproducts',
          dataType:"json", //to parse string into JSON object,
          success: function(data){ 
              if(data){
                  var len = data.length;
                  var txt = "";
                  if(len > 0){
                      for(var i=0;i<len;i++){
                          if(data[i].Name && data[i].Description){
                              txt += "<tr><td>"+data[i].Name+"</td><td>"+data[i].Description+"</td><td>"+data[i].Quantity+"</td></tr>";
                          }
                      }
                      if(txt != ""){
                          $("#table").append(txt).removeClass("hidden");
                      }
                  }
              }
          },
          error: function(jqXHR, textStatus, errorThrown){
              alert('error: ' + textStatus + ': ' + errorThrown);
          }
      });
      return false;
    });

但是当我尝试它时没有任何反应,并且 html 控制台页面没有显示任何错误:

html:

<button id="display">Display Products</button>
    <table id="table" class="hidden" style="display:none;">
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Description</th>
            <th>Image</th> 
        </tr>
    </table>

我希望输出是包含产品数据的表格

标签: node.jsajax

解决方案


你可以这样尝试:

Javascript:

$('#display').click(function() {
      $.ajax({
          type: 'GET',
          url: 'http://localhost:5000/listproducts',
          dataType:"json", //to parse string into JSON object,
          success: function(data) { 
              if(data) {
                for(let i=0;i<data.length;i++) {
                    $('#table tbody').append("<tr><td>"+data[i].Name+"</td><td>"+data[i].Description+"</td><td>"+data[i].Quantity+"</td></tr>");
                }
            }
          },
          error: function(jqXHR, textStatus, errorThrown){
              alert('error: ' + textStatus + ': ' + errorThrown);
          }
      });

      return false;
});

的HTML:

<button id="display">Display Products</button>
<table id="table" class="hidden" style="display:none;">
    <thead>
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Description</th>
            <th>Image</th> 
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

推荐阅读