简体   繁体   中英

Can't Fetch Data from REST call in BackBone: Uncaught TypeError: Cannot read property 'length' of undefined

I am having issues retrieving json data from a REST endpoint using Backbone. It will console.log the entire json source, but gives me an "Uncaught TypeError: Cannot read property 'length' of undefined" error for actual values within the JSON output. I am able to retrieve data as desired using a straight AJAX call to my REST endpoint as follows:

$.ajax({
    async: false,
    url: "http://myajaxcall.com/articles/featured",
    type: "GET",
    headers: { "Accept": "application/json;odata=verbose" },
    success: function (data) {
        $.each(data.aside, function (index, value) {
            console.log(value.headLine);
        });
    }
            });

But I am unable to get BackBone to fetch the same data. Where in my fetch am I going wrong?

    var featuredArticle = Backbone.Model.extend({
    defaults: {
        id: '',
        headLine: '',
        snippet: '',
        fullStory: '',
        location: '',
        nsfw: '',
        category: '',
        relatedArticleIds: '',
        hasVideoPlaceholder: '',
        numberOfImages: ''
    }
});
var featuredArticles = Backbone.Collection.extend({
    model: featuredArticle,
    url: 'http://myajaxcall.com/articles/featured'
});

var articleView = Backbone.View.extend({
    tagName: 'ul',
    render: function () {
        var that = this;
        var getfeaturedArticles = new featuredArticles();
        getfeaturedArticles.fetch({
            dataType:"json",
        success: function(data) {
            console.log(getfeaturedArticles);
            $.each(data.aside, function (index, value) {
                console.log(value.headline);
                $(that.el).append('<li>' + value.headLine + '</li>');
            });
        }
        })

        return this;
    }
});
var articles = new articleView();
$("body").append(articles.render().el);

The callback should be like this:

success: function(model, response)  {
    console.log(response);
}

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