0
votes

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);
1
I get the same error of: Uncaught TypeError: Cannot read property 'length' of undefinedKode
Are you using chrome? You can check the network tab to what you get back from the server. What you need to console log is the data parameter, not the collection object itself.html_programmer
Yes I am. Can you provide an example of logging the data parameter?Kode
That returns the entire json object. My issues is trying to get something from that object, such as the data for a headline.Kode
It has an array named aside that contains the property of headline. Any clue why my straight ajax call works for this, but the backbone fetch doesn't?Kode

1 Answers

1
votes

The callback should be like this:

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