Backbone.js getting data on POST request

2019-02-26 04:04发布

I am new to backbone.js.I am trying to POST data with my service and it returns me data. My service is: http://192.168.1.3:8080/app/search/candidate It takes Input as

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

And it returns list of users to me. so I created collection in backbone and tried My code is

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();

But it gives me Status Code: HTTP/1.1 415 Unsupported Media Type Where I am missing? Header for request from chrom debugger is

   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条回答
劫难
2楼-- · 2019-02-26 04:31

By default, Backbone requests media type "application/json", and it looks like your server can't handle that. To work around that, look into emaulateJSON http://backbonejs.org/#Sync-emulateJSON

查看更多
闹够了就滚
3楼-- · 2019-02-26 04:36

This code worked, see the request headers in the console is this 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();
        }
    });
查看更多
登录 后发表回答