简体   繁体   English

遍历AJAX响应

[英]Iterating over AJAX response

I'm trying to learn some front end engineering, but am getting caught up on what should be an easy thing to do. 我正在尝试学习一些前端工程,但是正赶上应该做的一件容易的事。 I've checked other questions, and tried the nested $each recommended 我检查了其他问题,并尝试了嵌套的$each建议

I have a simple REST API that I wrote that returns this JSON when the page loads: 我编写了一个简单的REST API,当页面加载时返回此JSON:

{"book":    
[{"authorFirstName":"Clive","authorLastName":"Cussler","genre":"Fiction","title":"Inca    
Gold"},{"authorFirstName":"Og","authorLastName":"Mandino","genre":"Self
Improvement","title":"The Greatest Salesman in the World"}, 
{"authorFirstName":"Bill","authorLastName":"O'Reilly","genre":"History","title":"Killing 
Lincoln"}]}

The problem is not getting this from the server; 问题不在于从服务器获取。 I get this when the page loads or when I go to the REST URL. 当页面加载时或当我进入REST URL时,都会收到此消息。 I'm having trouble rendering the page though. 我在呈现页面时遇到了麻烦。 Here's my AJAX call and success function: 这是我的AJAX调用和成功函数:

function getAllBooks() {
    console.log("Getting all books");
        $.ajax({
            type: 'GET',
            url: rootURL, 
            dataType: "json",
            success: renderBookList
        });
}

function renderBookList(data) {
    $('#bookList li').remove();
    $.each(data, function(index, book) {
        $('#bookList').append('<li><a href="#">' + book.title + '</a></li>');
    });
} 

If I change the line inside the $each function to be book[0].title , then I get the title for the first book in the JSON. 如果将$each函数内的行更改为book[0].title ,那么我将获取JSON中第一本书的标题。

What am I missing? 我想念什么? Is the issue with the JSON, that it's an object with one property (but the property is an array of objects)? JSON是否有问题,它是一个具有一个属性的对象(但该属性是一个对象数组)?

The server is JAX-RS and returns an ArrayList<Book> if that's germane. 服务器是JAX-RS,如果有关系,则返回ArrayList<Book> Thanks for any help. 谢谢你的帮助。

Your book array is referenced by the book property in your JSON response. book数组由JSON响应中的book属性引用。

function renderBookList(data) {
    $('#bookList li').remove();
    $.each(data.book, function(index, book) {
        $('#bookList').append('<li><a href="#">'+ book.title +'</a></li>');
    });
}

NOTE: You should be caching $('#bookList') in a variable instead of retrieving it for each iterations. 注意:您应该将$('#bookList')缓存在变量中,而不是每次迭代都检索它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM