从外部JSON中读取的主干脚本

Backbone script to read from external JSON

本文关键字:脚本 读取 JSON 从外部      更新时间:2023-09-26

我想使用主干脚本显示JSON中的数据。

这是html页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="backbone.js"></script>
<script src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

var Profile = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
    model: Profile,
    url: 'document.json'
});
var ProfileView = Backbone.View.extend({
    el: "#profiles",
    template: _.template($('#profileTemplate').html()),
    initialize: function(){
        this.listenTo(this.collection,"add", this.renderItem);          
    },
    render: function () {
        this.collection.each(function(model){
             var profileTemplate = this.template(model.toJSON());
             this.$el.append(profileTemplate);
        }, this);        
        return this;
    },
    renderItem: function(profile) {
         var profileTemplate = this.template(profile.toJSON());
         this.$el.append(profileTemplate);        
    }

});
var profileList = new ProfileList();
var profilesView = new ProfileView({ collection: profileList });
profilesView.render();

});
</script>
</head>
<body>
<div id="profiles"></div>
<script id="profileTemplate" type="text/template">
<div class="profile">
        <div class="info">
            <div class="name">
                <%= name %>
            </div>
            <div class="title">
                <%= title %>
            </div>
            <div class="background">
                <%= background %>
            </div>
        </div>
    </div>
                <br />
</script>
</body>
</html>   

这是我的json数据:document.json

[
{
    "id": "p1",        
    "name" : "AAAA",
    "title" : "BBBB",
    "background" : "CCCC"
},
{
    "id": "p2",
    "name" : "DDDD",
    "title" : "EEEE",
    "background" : "FFFF"
},
{
    "id": "p3",        
    "name" : "GGGG",
    "title" : "HHHH",
    "background" : "IIII"
}
]

页面上没有显示任何内容。
我错过什么了吗?我一直试图在指定的HTML中的div元素上打印JSON数据。但是什么也没有显示。我试着调试代码,我可以在Backbone.Model之前插入警告语句。在文档中扩展。jquery中的ready但是当我把alert语句放进去的时候,它并没有出现。因此,Backbone.Model中的代码。extend一定是哪里出错了。谁来帮帮我?

你需要检查你的脚本加载顺序,jquery应该是第一位的,下划线其次(因为你使用的是uncore .js模板),然后骨干:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>

如果这不能解决你的问题,那么你可以尝试发送一个静态引用到你的初始数据集,然后根据需要调用fetch()来获取更多的数据,或者你可以显式地调用fetch,如下所示:

var profileList = new ProfileList();    
var profilesView = new ProfileView({collection: profileList});
profileList.fetch();
profileList.bind('reset', function () {
   profilesView.render();
});
演示工作

你应该按顺序加载脚本,jquery,下划线,然后主干