node.js - 如何使用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>
我希望输出是包含产品数据的表格
解决方案
你可以这样尝试:
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>
推荐阅读
- dataframe - Pyspark:取消旋转具有多列的数据框,而无需对标题进行硬编码
- javascript - How can I trigger each link in a list of hyperlinks to animate on click (tap on touchscreens)
- javascript - 屏幕页面没有显示来自 React 的任何内容
- z3 - Z3 探测包含某个变量的子句
- python - 基于类的多环境 Django 设置
- node.js - nodejs:测试单独通过,一起运行时失败(mocha,sinon,aws-sdk)
- apache - htaccess中对同一文件的多个RewriteRules
- spring-boot - 使用 Testcontainers 和 Liquibase 时在测试之间重置数据库
- java - 密码验证方法成功,失败
- python - 标记一个盒子,考虑其内容的价值