2014-02-14 125 views
2

我是backbone.js.的新手,我試圖使用我的服務POST數據並返回數據。我的服務是:http://192.168.1.3:8080/app/search/candidate這需要輸入作爲Backbone.js在POST請求中獲取數據

{ 
    "skills":["c","java"] 
} 

,並返回用戶的名單給我。所以我在骨幹創建的集合,並試圖 我的代碼是

var UserModel = Backbone.Model.extend({ 
}); 

var EntityList = Backbone.Collection.extend({  
     model: UserModel, 
     url: `'http://192.168.1.3:8080/app/search/candidate'` 

     }); 



var View = Backbone.View.extend({ 

    el : '#mydiv', 
    template : _.template($("#details").html()), 
    initialize : function() { 
      var self = this;  
      this.coll = new EntityList(); 
     // this.coll.bind("reset", _.bind(this.render, this)); 
     this.coll.fetch({ 
     data:JSON.stringify({'skills':['c','java']}), 

     type: 'POST' , 

     success: function(){ 
       //console.log(this.coll.toJSON()); 
       self.render(); 
       }}); 
     } ,   

    render : function() { 
     // the persons will be "visible" in your template 
     this.$el.html(this.template({ persons: this.coll.toJSON() })); 
     return this; 
    } 

      }); 
var view = new View(); 

但它給我的狀態代碼:HTTP/1.1 415不支持的媒體類型 我在哪裏丟失的? 頭從CHROM調試請求

Request URL:http://192.168.1.3:8080/app/search/candidate 
Request Method:POST 
Status Code:415 Unsupported Media Type 
Request Headersview source 
Accept:application/json, text/javascript, */*; q=0.01 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:en-US,en;q=0.8 
Cache-Control:max-age=0 
Connection:keep-alive 
Content-Length:0 
Cookie:JSESSIONID=763119F314E1485DCC8B838F4539BA78 
Host:192.168.1.3:8080 
Origin:http://localhost:8080 
Referer:http://localhost:8080/jobSearch.html 
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/31.0.1650.63 Chrome/31.0.1650.63 Safari/537.36 
Response Headersview source 
Access-Control-Allow-Credentials:true 
Access-Control-Allow-Origin:http://localhost:8080 
Content-Length:0 
Date:Mon, 17 Feb 2014 11:46:00 GMT 
Server:Apache-Coyote/1.1 
+0

我找了幾件奇那裏:)是您的網址應該是這樣那個,額外的?另外,我不相信你需要'JSON.stringify'你的POST數據。您是否嘗試通過「http://192.168.1.3:8080」而不是「http:// localhost:8080」來提出請求?鉻可以挑剔與此。 – trenpixster

回答

3

此代碼工作,在控制檯看到的請求頭是這樣jsfiddle

this.coll.fetch({ 

     beforeSend: function (xhr) { 
      xhr.setRequestHeader('Content-Type', 'application/json'); 
     }, 

     data: JSON.stringify({'skills':['c','java']}), 

     type: 'POST', 

     success: function() { 
      //console.log(this.coll.toJSON()); 
      self.render(); 
     } 
    }); 
+0

狀態碼:415 Unsupported Media Type –

+0

Can你設置了一個jsfiddle?你在應用程序中設置了'Backbone.emulateJSON = true;'嗎?在調用fetch'console.log(Backbone.emulateJSON)之前,試着檢查它的值' –

+0

jsfiddle http://jsfiddle.net/PL8tn/ –

1

默認情況下,骨幹請求媒體類型「application/JSON」,它看起來像你的服務器不能處理這個問題。要解決這個問題,看看emaulateJSONhttp://backbonejs.org/#Sync-emulateJSON

+0

我的服務器正在處理應用程序/ json數據。我使用郵遞員工具對其進行了測試。並正常工作 –

+0

你確定你的郵遞員測試請求應用程序/ JSON? –

+0

是的,我確定我使用Content-Type:application/json對行數據進行了測試,它具有行數據{ 「skills」:[「c」,「java」] }並且正常工作 –