2013-01-13 2 views
1

서버 요청을 성공적으로 수행하는 백본 모델이 있습니다. 콜백은 백본의 트리거 메서드를 사용하여 연결된 뷰에서 이벤트를 트리거하고 백본 문서에 설명 된대로 트리거 된 메서드의 두 번째 매개 변수로 서버 요청의 구문 분석 된 json 응답을 전달합니다. 뷰에서 이벤트는 render 메소드를 트리거하지만 응답 오브젝트는 뷰에서 널입니다. 이 오류가 발생했습니다parseJSON (응답)이 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); 

에게 렌더링 방법을 렌더링하는 렌더링 방식을 트리거 뷰의 초기화 방법에있어서, 이벤트의 서버 요청 응답이 null 인 경우

이 중요한 경우
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 변수가 null입니다. 내가 뭘 잘못하고 있는지 알 겠어?

var json = $.parseJSON(response); 
console.log(json) 

응답 응답 객체에 parseJSON를 호출 할 필요가 실제로 없었다

Object {word: Array[6]} 
word: Array[6] 
__proto__: Object 
+0

'$ .parseJSON' 시도하기 전에'response'에 무엇이 있습니까? –

+0

@muistooshort OP의 끝 부분에 추가 한 객체입니다. 웬일인지 나는 그것을 해석 할 필요가 없다. 나는이 코드를 신트라 (sintra) 앱의 레일즈 앱에 적용하고있다. sinatra를 위해 만든 사람이 응답 객체를 파싱했습니다. – BrainLikeADullPencil

+0

Content-Type 헤더가 정확하다면 JSON이 자동으로 구문 분석되어야합니다. 아마도 Sinatra가 올바르게 설정하지 않았을 수 있습니다. 아마,'.parseJSON'에 문자열이 아닌 문자열을 넘겨 주면 문제가 생길 수도 있습니다. –

답변

0

. 단어 속성을 응답 객체에서 직접 가져올 수 있으므로 방금 응답 객체를 두 번째 인자로 전달하여보기에 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); 
     } 
     }) 
    }, 
관련 문제