2

我可以得到以下格式的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');
    });
}

请问上面的代码是否正确?

4

2 回答 2

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');
});
于 2013-03-17T16:53:50.743 回答
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');
    });
}
于 2013-03-17T16:57:20.260 回答