我是jQuery数据表的新手,并且在ajax调用返回数据时遇到问题。如何使用数据集填充表格?我需要填补div。它的结构与表格相似:
<div id="wrap">
<div class="drow">
<div class="dcol1">
/*data*/
</div>
<div class="dcol2">
/*data*/
</div>
</div>
<div class="drow">
<div class="dcol1">
/*data*/
</div>
<div class="dcol2">
/*data*/
</div>
</div>
<div class="drow">
<div class="dcol1">
/*data*/
</div>
<div class="dcol2">
/*data*/
</div>
</div>
</div>
有什么想法吗?
答案 0 :(得分:0)
你可以像下面那样遍历div,
$('#wrap .drow').each(function(){
//populate the dcol1
$(this).find('.dcol1').text(desiredData);
//populate the dcol2
$(this).find('.dcol2').text(desiredData);
});
需要看到响应json结构以帮助进一步。
现在,让json响应具有以下结构,
{
data: [
{
"dcol1": "some data1",
"dcol2": "some data1"
},
{
"dcol1": "some data2",
"dcol2": "some data2"
},
.........
{
"dcol1": "some dataN",
"dcol2": "some dataN"
}
]
}
所以,你可以像下面这样做,
var resp; //your json response
var dataArr = resp.data;
$('#wrap .drow').each(function(index){
//populate the dcol1
$(this).find('.dcol1').text(dataArr[index].dcol1);
//populate the dcol2
$(this).find('.dcol2').text(dataArr[index].dcol2);
});
答案 1 :(得分:0)
我不知道,你是如何得到回应的。 但在这里,它可能对你有帮助。
$.ajax ({
type : "GET",
url : "your web service url",
cache : false,
success: function(res) {
$.each(res,function(i, index) {
var responseObject = res[i];
$("#wrap").empty();
$("#wrap").append(' <div class="drow"> <div class="dcol1">responseObject.firstName</div><div class="dcol2">responseObject.firstName</div> </div> ');
});
//it will loop through your response object and append data as per your format
},
error : function(e){
alert("Something goes wrong");
}
}); //ajax call ends
答案 2 :(得分:0)
我已经为您的帮助设置了示例,请检查并告诉我是否需要进一步的帮助!
请注意,我将返回数据用作 JSON 格式。
JSON:
[{"drow":[{"dcol1":"dcol1_value","dcol2":"dcol2_value"}]},
{"drow":[{"dcol1":"dcol1_value","dcol2":"dcol2_value"}]}]
HTML:
<div id="wrap"></div>
JQ:
$(document).ready(function() {
var d= [{"drow":[{"dcol1":"dcol1_value","dcol2":"dcol2_value"}]},
{"drow":[{"dcol1":"dcol1_value","dcol2":"dcol2_value"}]}];
//loop over items of d
$.each(d,function(index, item){
drowDiv = '';
dcol1Div = '';
dcol2Div = '';
$.each(item.drow,function(subIndex, subItem){
dcol1Div = '<div class="dcol1">' + subItem.dcol1 + '</div>';
dcol2Div = '<div class="dcol2">' + subItem.dcol2 + '</div>';
drowDiv = '<div class="drow">' + dcol1Div + dcol2Div + '</div>';
});
$("#wrap").append(drowDiv);
});
});
结果:
<div id="wrap">
<div class="drow">
<div class="dcol1">dcol1_value</div>
<div class="dcol2">dcol2_value</div>
</div>
<div class="drow">
<div class="dcol1">dcol1_value</div>
<div class="dcol2">dcol2_value</div>
</div>
</div>
此内容也在jsFiddle处有效。