使用jQuery迭代和显示JSON数据 [英] Iterating and displaying JSON data with jQuery
问题描述
我必须在html表中显示一组记录。我正在使用PHP和jQuery。
这是我的结果集,使用 json_encode()
检索这是beta.php的输出
I have to display a set of records in a html table. I'm using PHP and jQuery for this.
This is my result set which is retrieved using json_encode()
This is the output of beta.php
[{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"},{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"},{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"},{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}]
我正在使用 print.html
页面将以上结果打印在表格中
I'm using a print.html
page as follows to print the above results in a table
$(document).ready(function(){
$getJSON('beta.php' , function(data){
$.each(data, function(){
$.each(this , function(key , value){
$("<table>").appendTo("document.body");
$("<table>").html("<tr><td>" + value.StuId + "</td><td>" + value.fName + "</td><td>" + value.lName + "</td><td>" + value.age + "</td><td>" + value.grade + "</td></tr>");
});
});
});
});
这会产生错误,说 $ getJSON()未定义
如果有人能帮助我,我将不胜感激。
I would be grateful if someone could please help me.
当我按如下方式更改代码时,我能够打印记录集中的第一条记录。
但我不明白为什么$ .each()不会工作????
Well when I changed the code as follows I'm able to print the first record in the record set.
But I do not understand why the $.each() wont work????
$("table").html("<tr><td>" + data[0].StuId + "</td><td>" + data[0].fName + "</td><td>" + data[0].lName + "</td><td>" + data[0].age + "</td><td>" + data[0].grade + "</td></tr>");
我也试过使用for循环但是它只打印了最后一行
I tried using a for loop too but then it prints only the last row
$.getJSON('beta.php' , function(data){
$.each(data, function(key, value){
for(var x=0; x < data.length; x++){
$("table").html("<tr><td>" + data[x].StuId + "</td><td>" + data[x].fName + "</td><td>" + data[x].lName + "</td><td>" + data[x].age + "</td><td>" + data[x].grade + "</td></tr>");
$("table").appendTo("document.body");
}
});
})
任何人都可以对此发表意见:)
Can anyone please give your opinion on this :)
推荐答案
尝试
$.getJSON("beta.php", function(data) {
var table = $("<table>").appendTo(document.body);
$.each(data, function(i, row) {
var tr = $("<tr>").appendTo(table);
$("<td>").appendTo(tr).html(row.StuId);
$("<td>").appendTo(tr).html(row.fName);
$("<td>").appendTo(tr).html(row.lName);
$("<td>").appendTo(tr).html(row.age);
});
});
干杯
这篇关于使用jQuery迭代和显示JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!