我的Backbone.js应用程序在页面加载时抛出JSON.Parse语法错误

时间:2013-01-15 03:15:44

标签: javascript jquery json backbone.js icanhaz.js

我正在尝试使用Backbone.js编写的品牌打击新界面替换现有的Web应用程序。最终,这将是非常棒的,因为应用程序由使用Python + CherryPy编写的restful API支持,并且不喜欢刷新主机页面。

我的第一步是尝试使用关于'net的各种教程,将一些Backbone.js概念证明放在一起。这就是我想出的:

<!DOCTYPE html>
<html>
<head>
    <script type="application/javascript" src="/static/js/jquery-1.8.2.min.js"></script>
    <script type="application/javascript" src="/static/js/underscore-min.js"></script>
    <script type="application/javascript" src="/static/js/json.js"></script>
    <script type="application/javascript" src="/static/js/ICanHaz.min.js"></script>
    <script type="application/javascript" src="/static/js/backbone.js-0.9.9-min.js"></script>

    <script type="application/javascript">
        $(function() {
            //logical model of a user
            var User = Backbone.Model.extend({});

            //visual representation of a user
            var CurrentUserView = Backbone.View.extend({
                render: function() {
                    this.el = ich.user(this.model.toJSON());
                    return this;
                }
            })

            //create a user and drop its representation into the DOM
            var currentUser = new User({username: "hello world"});
            var view = new CurrentUserView({model: currentUser});
            $('.content').append(view.el.render());
        });
    </script>
</head>
<body>
    <div class='content'>
        <p>The user representation should show up below this paragraph</p>
    </div>

    <!--ICanHaz user template -->
    <script id="user" type="text/html">
        <ul class="user">
            <li><a href="#">{{ username }}</a></li>
            <li><a href="#" id="logout">logout</a></li>
        </ul>
    </script>
</body>
</html>

不幸的是,当我在Firefox中加载此页面时,用户表示不会显示在.content div内部,并且错误消息SyntaxError: JSON.parse: unexpected character会显示在Web控制台中。

这个问题似乎与CurrentUserView有关,因为以下代码完全符合我的要求:

$(function() {
    //logical model of a user
    var User = Backbone.Model.extend({});

    //create a user and drop its representation into the DOM
    var currentUser = new User({username: "hello world"});
    $('.content').append(ich.user(currentUser.toJSON()));
});

这里发生了什么?

2 个答案:

答案 0 :(得分:1)

不确定为什么这会给您一个解析错误,但我认为$('.content').append(view.el.render());应为$('.content').append(view.render().el);

答案 1 :(得分:1)

经过一夜安眠和第二次代码传递后,看起来我已经下载了json库而不是所需的json2库。现在一切都按预期工作了。