1
我有一個成功的服務器請求的Backbone模型。回調是使用主幹的觸發方法觸發相關視圖中的事件,並將其從服務器請求傳遞解析的json響應作爲觸發方法的第二個參數,如主幹文檔中所述。在視圖中,該事件觸發渲染方法,但視圖中的響應對象爲null。它拋出這個錯誤parseJSON(響應)爲空
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);
}
})
},
在視圖的初始化方法,其觸發render方法來呈現響應
this.model.on("gameStartedEvent", this.render, this);
render方法事件的服務器請求響應爲空的地方
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'之前有什麼'響應'嗎? –
@ muistooshort我已添加到OP末尾的對象。出於某種原因,我不必解析它來調用它。我只是將這些代碼從sintra應用程序調整爲rails應用程序。爲sinatra製作的人解析了響應對象。 – BrainLikeADullPencil
如果Content-Type標頭正確,則JSON應自動分析,可能Sinatra沒有正確設置。據推測,喂一個非字符串''.parseJSON'給你一個'空'你的麻煩。 –