我有一个看起来像这样的JSON
{
secInfo: [
{
loginResult: 1,
userId: "admin",
userName: "admin",
userpassword: "ramshyam"
},
{
address: "",
loginResult: 1,
userEmail: "",
userId: "anuraag",
userName: "Anuraag",
userpassword: "kk0903"
}
]
}
当我使用下面的jquery代码在表中显示数据时,它会用“undefined”填充表格
<script>
$(document).ready(function(){
//attach a jQuery live event to the button
$('#submitlogin').live('click', function(){
$.getJSON('/acc/services/json/security/loginresult.json', function(data) {
//alert(data); //uncomment this for debug
//alert (data.item1+" "+data.item2+" "+data.item3); //further debug
// $('#showdata').html("<p>Result="+data.loginResult+" userid="+data.userId+" username="+data.userName+"</p>");
$.each(data.secInfo, function(){
$('#usertable').append(
function(this){
return "<tr>"+
"<td>"+this.userId+"</td>"+
"<td>"+this.userName+"</td>"+
"<td>"+this.userpassword+"</td>"+
"<td>1</td>"+
"<tr>";
}
);
})
});
});
});
</script>
我是jquery的新手,并从http://forum.jquery.com/topic/jquery-create-table-from-json-data这篇帖子中得到了一些想法。
请帮帮我
答案 0 :(得分:0)
问题可能是函数回调中的“this”,即保留关键字。另外,尝试将JSON条目作为数组而不是类属性进行访问。
答案 1 :(得分:0)
这个&#39;的范围我猜想已经改变了。试试这个:
$(document).ready(function(){
//attach a jQuery live event to the button
$('#submitlogin').live('click', function(){
$.getJSON('/acc/services/json/security/loginresult.json', function(data) {
//alert(data); //uncomment this for debug
//alert (data.item1+" "+data.item2+" "+data.item3); //further debug
// $('#showdata').html("<p>Result="+data.loginResult+" userid="+data.userId+" username="+data.userName+"</p>");
$.each(data.secInfo, function(dataItem){
$('#usertable').append(
function() {
return "<tr>"+
"<td>"+dataItem.userId+"</td>"+
"<td>"+dataItem.userName+"</td>"+
"<td>"+dataItem.userpassword+"</td>"+
"<td>1</td>"+
"<tr>";
}
);
})
});
});
});
答案 2 :(得分:0)
这肯定有效
<script>
$(document).ready(function(){
//attach a jQuery live event to the button
$('#submitlogin').live('click', function(){
$.getJSON('/acc/services/json/security/loginresult.json', function(data) {
var genericlist = eval('(' + data+ ')');
var table = document.getElementById("usertable");
var tabledata = "";
for(i=0;i<genericlist.secInfo.length;i++){
tabledata += "<tr>";
tabledata += "<td>" + genericlist.secInfo[i].useID += "</td>";
tabledata += "<td>" + genericlist.secInfo[i].useName += "</td>";
tabledata += "<td>" + genericlist.secInfo[i].usePassword += "</td>";
tabledata += "</tr>";
}
table.innerHTML = tabledata;