【问题标题】:parseJSON(response) is nullparseJSON(response) 为空
【发布时间】: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


【解决方案1】:

实际上不需要在响应对象上调用 parseJSON。我可以直接从响应对象中获取单词属性,所以我只是将响应对象作为第二个参数传递给触发器,并在视图中调用response.word

 $.ajax({
        url: "/gamestart",
        type: "GET",
        success: function(response) {
          console.log(response.word);
          var json = $.parseJSON(response);    ####unnecessary to parseJSON here
          console.log(json);

          _this.set({lost: false});
          _this.set({win: false});
          _this.trigger("gameStartedEvent", response);
        }
      })
    },

【讨论】:

    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多