2012-01-15 48 views
2

有誰知道如何指定Post的jQuery /應用程序的ContentType?我以爲自己是,骨幹在默認情況下是這樣做的,但根據事實說它得到純文本(請參閱評論),我想我需要找出另一種方式來指定它。Backbone.js後500錯誤

我正在使用Backbone.js,我試圖發佈到不再只讀的TastyPie API,當我嘗試製作模型和.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

這就是「常規」 backbone.sync吧?你會得到什麼樣的500迴應?我最近做了一個應用程序,結合了tastypie和主幹。你可以看看這裏:https://github.com/c4urself/ratebeer也許它會給你一些想法。 – c4urself 2012-01-15 11:33:22

+0

:「格式爲'text/plain'沒有可用的反序列化方法,請檢查你的序列化程序中的''formats''和'content_types'」, – user784756 2012-01-15 11:45:28

+0

這裏的一個障礙是,儘管Paul的解決方案是正確的, Tastypie還不支持X-HTTP-Method-Override標頭。你可以使用類似這樣的東西來添加或直接使用覆蓋的方法擴展你正在使用的Resource類:https://gist.github.com/2161338 – 2012-03-22 18:55:48

回答

3

嘗試在你的代碼中設置Backbone.emulateJSON = true;

如果設置爲true,那麼它會將contentType設置爲您正在查找的「application/json」。

你只需要一次設置此變量,所以一個好的地方就上述表單提交的代碼

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