我可以使用以下格式获取json
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}]
如何使用数据显示如下图所示,第一行是用户名,第二行是书
<button type="button" id="test">Test 123</button>
<ul id="studentList" data-role="listview" data-filter="true"></ul>
var serviceURL = "http://mydomain.com/";
var students;
$("#test").click(function()
{
getStudentList();
});
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
students = data.user_name;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.user_name + ' ' + student.password + '</h4>' +
'<p>' + student.user_name + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}
我可以问上面的代码是否正确吗?
答案 0 :(得分:1)
您将响应命名为data
..因为您的响应位于数组[]
中,您必须首先循环data
..再次获取其数据对象..
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
//-^^^^---here
并在循环中获取相应的名称和密码对象...您可以通过.
运算符获取该对象..所以在内循环中,student.data.user_name
为您提供用户名,student.data.book
为您提供书和其他人类似......
试试这个......
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
//students = data.user_name;
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name +'</h4>' + //here get username
'<p>' + student.data.book + '</p>' + //here get book
'</li>');
});
$('#studentList').listview('refresh');
});
答案 1 :(得分:1)
我根据您的输入完成了这样做,您只需将其包含在您的代码中即可。我不知道你的意思是'第二行是书',因为你的json输入中没有包含书籍+你正试图访问'student.data.password',这也是输入中没有的。 简单版本的jsFiddle http://jsfiddle.net/2KMd9/
var json =[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}];
var students = json;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
满足您的需求:
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}