2012-01-15 3 views
2

누구든지 json/애플리케이션에 대한 게시물의 ContentType을 지정하는 방법을 알고 있습니까? 필자는 내가 원래 백본이라고 생각 했었지만 백본은 기본적으로 그렇게했지만, 평범한 텍스트 (주석 참조)를 얻고 있다고 말하는 것으로 판단 할 때 다른 방법을 지정해야한다고 생각합니다.Backbone.js Post 500 Error

Backbone.js를 사용하고 있으며 더 이상 읽기 전용이 아닌 TastyPie API를 POST하려고하는데 모델을 만들고 .save()하려고 할 때 500 오류가 발생합니다. http://documentcloud.github.com/backbone/docs/backbone.html#section-124

Backbone.sync = function(method, model, options){ 
     var type = methodMap[method]; 
     var params = _.extend({ 
     type: type, 
     dataType: 'json' 
     }, options); 

     if (!params.url){ 
     params.url = getUrl(model) || urlError(); 
     } 

     if (Backbone.emulateJSON){ 
     params.contentType = 'application/json'; 
     params.data = params.data ? {model: params.data} : {}; 
     } 

     if (Backbone.emulateHTTP){ 
     if(type === 'PUT' || type === 'DELETE'){ 
      if (Backbone.emulateJSON) params.data._method = type; 
      params.type = 'POST'; 
      params.beforeSend = function (xhr){ 
       xhr.setRequestHeader('X-HTTP-Method-Override', type); 
      }; 
     } 
     } 

     if (params.type !== 'GET' && ! Backbone.emulateJSON){ 
     params.prorcessData = false; 
     } 

     return $.ajax(params); 
     }; 





    $.fn.serializeObject = function() 
    { 
     var o = {}; 
     var a = this.serializeArray(); 
     $.each(a, function() { 
     if (o[this.name] !== undefined) { 
      if (!o[this.name].push) { 
      o[this.name] = [o[this.name]]; 
      } 
      o[this.name].push(this.value || ''); 
     } else { 
      o[this.name] = this.value || ''; 
     } 
     }); 
     return o; 
    }; 

    $(function() { 
     $('form').submit(function() { 
     var dict = $('form').serializeObject(); 
     var new_task = new Backbone.Model({ 
     date: toString(dict.date), 
     name: toString(dict.name), 
     priority: toString(dict.priority)}); 
     console.log("new_task =" + new_task); 
     new_task.save(); 
     console.log(dict); 

     return false; 
     }); 

    }); 


    }); 
+0

제출 바로 폼 위에? 어떤 500 개의 반응을 얻습니까? 나는 최근 tastypie와 백본을 결합한 앱을 만들었다. 당신은 그것을 여기에서 확인할 수있다 : https://github.com/c4urself/ratebeer 어쩌면 그것은 당신에게 약간의 아이디어를 줄 것이다. – c4urself

+0

: " 'text/plain'형식의 사용 가능한 직렬화 해제 방법이 없습니다. serializer에서''formats'' 및''content_types''를 확인하십시오.", – user784756

+0

여기서 한가지 장애물은 폴의 해결책이 맞지만, Tastypie는 아직 X-HTTP-Method-Override 헤더를 지원하지 않습니다. 다음과 같이 무효화 된 메소드를 사용하여 Resource 클래스를 추가하거나 직접 확장 할 수 있습니다. https://gist.github.com/2161338 –

답변

3

코드에서 Backbone.emulateJSON = true;을 설정하십시오 :이 내가 여기 나의 동기에 내가 사용하고 코드 조각입니다.

true로 설정하면 contentType을 찾고있는 'application/json'으로 설정합니다.

한 번만이 변수를 설정할 필요가

, 그래서 좋은 장소는 코드 "일반"backbone.sync 권리의

$(function() { 
    Backbone.emulateJSON = true; 
    $('form').submit(function() { 
     ...