0

Note: I reformulated this post after solving my original problem because I immediately ran into another problem that can fit under the same title. First I'll summarize the first problem and my solution, then continue with the second problem.

My Wordpress 3.8 installation was set to work with Jetpack's JSON API. But my backbone.js GET requests were canceled (indicated by Google Chrome's Network Panel). Furthermore, I got this report in the console:

XMLHttpRequest cannot load http://public-api.wordpress.com/rest/v1/sites/americawasnotfree.org/posts/?category=life-after-the-treaties. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://americawasnotfree.org' is therefore not allowed access.

Solution: Use the JSON API plugin from dphiffer instead of Jetpack's solution.

NEW ISSUE: Now even though I get the data, I have not figured out how to work with it using Underscore's templating framework. I'm following this tutorial. Below is my broken code (which includes code suggested by Dato'), and below that is what I've tried.

    <div class="posts"></div>

    <script type="text/template" id="posts-list-template">
        <div>Here is the...</div>
        <% _.each(yourListPosts, function(yourListPost) { %>
        <%= yourListPost.get('title') %>
        <% }); %>
    </script>

<script type="text/javascript">
(function($){
$( document ).ready(function() {

    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
      options.url = '//americawasnotfree.org/api/' + options.url;
    });

    var Post = Backbone.Model.extend({});
    var Posts = Backbone.Collection.extend({
        model: Post,
        url:'get_category_posts/?slug=life-after-the-treaties/'
    });

    var PostsList = Backbone.View.extend({
        el: '.posts',
        render: function() {
            var that = this;
            var posts = new Posts();
            posts.fetch({
                success: function(posts) {
                        var template = _.template($('#posts-list-template').html(), {
                            yourListPosts: that.collection.models
                        });
                    that.$el.html(template);
                }
            })
        }
    });

    var Router = Backbone.Router.extend({
        routes: {
          "": "category"
        }
    });

    var postsList = new PostsList();

    var router = new Router();
    router.on('route:category', function() {
        postsList.render();
    });
    Backbone.history.start();
});
})(jQuery);
</script>

I have modified the #posts-list-template in several ways:

  1. Passed posts as the data argument in _.template(), then tried traversing the object using bracket notation: posts["responseJSON"]["posts"][0]["content"]. (If I assign the returned object to a variable from Google Chrome's console, I can get the the "content" of post number 0 using this notation.

  2. Passed the fetched data through jQuery.parseJSON( data ) (thinking the data might not be correctly parsed).

  3. I know _.template() is correctly passing templates. The function succeeds in displaying a div and sample text when placed in #posts-list-template.

0

I managed to display the data returned from JSON using the code below.

Note that I used JavaScript bracket notation to access the posts array rather than Backbone's .get method. Also note that the object fetched is passed to a variable called posts, which is then passed to _.template. I'm betting it's this that prevents me from using Backbone's .get method, but I'll save the question for a separate thread.

<script type="text/template" id="posts-list-template">
    <div>Here is the...</div>
    <% _.each(posts, function(post) { %>
        <div><%= post['title'] %></div>
        <%= post.content %>
    <% }); %>

</script>

<script type="text/javascript">
(function($){
$( document ).ready(function() {

    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
      options.url = '//americawasnotfree.org/api/' + options.url;
    });

    var Posts = Backbone.Collection.extend({
        url:'get_category_posts/?slug=life-after-the-treaties/'
    });
    var PostsList = Backbone.View.extend({
        el: '.posts',
        render: function() {
            var that = this;
            obj = new Posts();
            obj.fetch({
                success: function() {
                    posts = obj["models"][0]["attributes"]["posts"];
                    var template = _.template($('#posts-list-template').html(), posts );
                    that.$el.html(template);
                }
            })
        }
    });

    var Router = Backbone.Router.extend({
        routes: {
          "": "category"
        }
    });

    var postsList = new PostsList();

    var router = new Router();
    router.on('route:category', function() {
        postsList.render();
    });
    Backbone.history.start();
});
})(jQuery);
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.