【发布时间】:2013-01-13 15:53:15
【问题描述】:
我有一个 Backbone 模型正在发出成功的服务器请求。回调是使用主干的触发方法来触发关联视图中的事件,并将服务器请求中解析的 json 响应作为触发方法的第二个参数传递,如主干文档中所述。在视图中,事件触发了render方法,但是视图中的响应对象为null。它抛出了这个错误
Uncaught TypeError: Cannot read property 'word' of null
谁能看出我做错了什么?
来自模型的服务器请求
new: function() {
var _this = this;
console.log("new function of model");
$.ajax({
url: "/gamestart",
type: "GET",
success: function(response) {
console.log(response);
var json = $.parseJSON(response);
_this.set({lost: false});
_this.set({win: false});
_this.trigger("gameStartedEvent", json);
}
})
},
视图的初始化方法中触发渲染方法渲染响应的事件
this.model.on("gameStartedEvent", this.render, this);
响应为空的渲染方法
render: function(response) {
$("#hint").show();
console.log(response);
var html = this.template({characters: response.word});
this.el.hide();
this.el.html(html).show();
},
注意,如果重要的话,视图是用模型实例化的
var word_view = new WordView({model: game})
更新
实际上错误发生在这里。响应成功返回,但我解析不正确。当我检查控制台时,变量 json 为空。你能看出我做错了什么吗?
var json = $.parseJSON(response);
console.log(json)
回应
Object {word: Array[6]}
word: Array[6]
__proto__: Object
【问题讨论】:
-
在您尝试
$.parseJSON之前,response中有什么内容? -
@muistooshort 我添加到 OP 末尾的对象。出于某种原因,我不必解析它来调用它。我只是将此代码改编为来自 sintra 应用程序的 rails 应用程序。为 sinatra 制作它的人解析了响应对象。
-
如果 Content-Type 标头正确,则应该自动解析 JSON,可能是 Sinatra 没有正确设置它。据推测,将非字符串提供给
$.parseJSON会给你一个null来解决你的麻烦。
标签: backbone.js