我从Web服务获取json字符串,并希望在html页面中显示。我使用ajax动态显示表中的行。但问题是所有记录都存在于单行中。
代码:
function showall(){
var user = document.getElementById("user_name").value;
alert(user);
var row = $("<tr>");
var nextrow = $("</tr>");
$.ajax({
type: "POST",
url: "webresources/hello/showrequests",
data : user,
success : function(data){
console.log(data);
$.each(data, function(index, store){
$.each(store, function(key,value){
row.append($("<td>").html(value));
});
$('#requests').append(row);
$('#requests').append(nextrow);
});
},
error: function(e){
alert("error"+e+"has occured");
}
});
}
和html body
<body onload="showall();">
<h1><%=user%></h1>
<input type="hidden" value="<%=user%>" id="user_name">
<table border="1" id="requests" style="border-collapse: collapse">
<tr>
<th>RequestId</th>
<th>Request</th>
<th>Category</th>
<th>Subcategory</th>
<th>Department</th>
<th>Status</th>
</tr>
</table>
</body>
输出就像
col11 | col12 | col13 | col21 | col22 | col23|
我期待像
col11 | col12 | col13 |
col21 | col22 | col23|
我从网络服务发送的JSONArray就像
[{"requestid":1,"request":"Increase RAM from 4GB to 8GB","category":"Hardware","subcategory":"To increase the RAM","department":"System","status":"Pending for approval"},{"requestid":2,"request":"Increase RAM from 2GB to 4GB\n","category":"Hardware","subcategory":"To increase the RAM","department":"System","status":"Pending for approval"},{"requestid":3,"request":"Increase RAM from 1 GB to 4 GB","category":"Hardware","subcategory":"To increase the RAM","department":"System","status":"Pending for approval"}]
我需要在ajax中做些什么? 谢谢
答案 0 :(得分:1)
嗯,问题在于我认为该行是在循环之外获取的。所以基本上你要添加到该行,附加它,然后重新使用同一个对象(使用之前的附加)来完成下一轮数据追加。您需要每次(在循环内)创建新的行对象。
更新: 见jsbin
function showall(){
var user = document.getElementById("user_name").value;
$.ajax({
type: "POST",
url: "webresources/hello/showrequests",
data : user,
success : function(data){
$.each(resp, function(index, store){
var tr = $('<tr></tr>');
$.each(store, function(key,value){
tr.append($('<td></td>').html(value));
});
$('#requests').append(tr);
});
},
error: function(e){
alert("error"+e+"has occured");
}
});
}
答案 1 :(得分:0)
你可以移动这一行
$('#requests').append(row);
前
$.each(store, function(key,value){
答案 2 :(得分:0)
success : function(data){
console.log(data);
$.each(data, function(index, store){
$('#requests').append(row);
$.each(store, function(key,value){
$('#requests').append($("<td>").html(value));
});
$('#requests').append(nextrow);
});
答案 3 :(得分:0)
我建议这样做,这样就不必对元素进行解析了。首先使用html创建一个字符串,然后将其添加到dom。
var html = '';
$.each(data, function(index, store){
html += '<tr>';
$.each(store, function(key,value){
html += '<td>'+value+'</td>';
});
html+= '</tr>';
});
$('#requests').append(html);