Backbone.js获取POST请求的数据

时间:2014-02-14 04:50:40

标签: rest backbone.js jax-rs

我是backbone.js.的新手。我正在尝试使用我的服务POST数据,它会返回数据。我的服务是:http://192.168.1.3:8080/app/search/candidate输入为

{
  "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

2 个答案:

答案 0 :(得分: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();
        }
    });

答案 1 :(得分:1)

默认情况下,Backbone请求媒体类型“application / json”,看起来你的服务器无法处理。要解决此问题,请查看emaulateJSON http://backbonejs.org/#Sync-emulateJSON