简体   繁体   中英

Ajax get undefined List from restful API

I tried search first but no fix. here is my jQuery code.

 var rootUrl = "http://" + window.location.host + "/Blog/rest/posts"; var allPosts = function() { $.ajax({ type : 'GET', url : rootUrl, dataType : "json", success : renderAllPosts }); }; var renderAllPosts = function(data) { $.each(data, function(index, post) { alert(data); // returns [object Object] alert(post); // returns [object Object],[object Object] $('#allPosts').append( '<a href=posts/' + post.ID + '><h3 id="animation_style">' + post.title + '</h3></a><hr>'); }); } $(document).ready(function() { // alert(window.location.host); allPosts(); }); 

Here is the data that rootUrl returns 在此处输入图片说明

When I only have one record in database it works fine... I have no idea why alert(post) returns two objects. I think it should be alert(data) returns two objects.

keep getting this 在此处输入图片说明

your data, has an attribute called postModel, you should change this:

var renderAllPosts = function(data) {
    $.each(data, function(index, post) {
        alert(data); // returns [object Object]
        alert(post);    // returns [object Object],[object Object]
        $('#allPosts').append('<a href=posts/' + post.ID + '><h3 id="animation_style">'+ post.title + '</h3></a><hr>');
    });
}

For:

var renderAllPosts = function(data) {
    $.each(data.postModel, function(index, post) {
        alert(data); // returns [object Object]
        alert(post);    // returns [object Object],[object Object]
        $('#allPosts').append('<a href=posts/' + post.ID + '><h3 id="animation_style">'+ post.title + '</h3></a><hr>');
    });
}

That way, you'll cycle through the array of posts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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