unkn0wn unkn0wn - 26 days ago 9
JSON Question

How do i pass PHP's JSON_ENCODE array into underscore loop

I am getting a long array from PHP containing various data objects.

[{"commid":"1","uid":"0","pid":"3","comment":"comm","parid":null,"date":"2016-10-27 15:03:10"},
{"commid":"2","uid":"0","pid":"10","comment":"Ana","parid":null,"date":"2016-10-27 15:03:51"},
{"commid":"3","uid":"0","pid":"5","comment":"asss!","parid":null,"date":"2016-10-27 15:05:50"},
{"commid":"4","uid":"0","pid":"10","comment":"Lawl?","parid":null,"date":"2016-10-27 17:03:59"},
{"commid":"5","uid":"0","pid":"14","comment":"sd","parid":null,"date":"2016-11-06 00:25:04"},
{"commid":"6","uid":"0","pid":"14","comment":"sds","parid":null,"date":"2016-11-06 00:25:50"},
{"commid":"7","uid":"0","pid":"14","comment":"WOW!","parid":null,"date":"2016-11-08 15:06:18"},
{"commid":"8","uid":"0","pid":"13","comment":"Hello!?","parid":null,"date":"2016-11-08 15:14:30"}]


My Backbone View which will be rendering the data is

var WorkPage = Backbone.View.extend({
el: $('#indexcontent'),
render: function () {
Backbone.history.navigate('work');
var _this = this;

this.$el.html(workHTML);
$.ajax({
type: "GET",
url: "includes/server_api.php/work",
data: '',
cache: false,
success: function (html) {
console.log(html);
var compiledTemplate = _.template($('#content-box').html(), html);
_this.$el.html(compiledTemplate);
},
error: function (e) {
console.log(e );
}
});
return false;



}
});


My workHTML which will be rendered by Underscore is

<script type="text/template" id="content-box">
<div class="workhead">
<h3 class="msg comment"><%= comment%></h3>
<p class="date"><%= date%></p>
</div>
</script>
<div id="content-box-output"></div>


How do i implement a underscore loop here?

Answer

Here is one way to load the template for each value in the data array.

var WorkPage = Backbone.View.extend({
        el: $('#indexcontent'),
        render: function () {
            Backbone.history.navigate('work');
            var _this = this;

            this.$el.html(workHTML);        
                $.ajax({
                    type: "GET",
                    url: "includes/server_api.php/work",
                    data: '',
                    cache: false,
                    success: function (data) {
                        console.log(data);
                        var $div = $('<div></div>');
                        _.each(data, function(val){
                          $div.append(_.template($('#content-box').html(), val));
                        });                        
                        _this.$el.html($div.html());
                    },
                    error: function (e) {
                        console.log(e );
                    }
                });
                return false;
        }
    });

Comments