I'm trying to get backbone to do a POST when I call fetch on a model, but nothing I've tried so far seems to work. I also need to pass multiple parameters in the fetch (not just an ID), and need to use jsonp.
I tried overriding the sync method in the model to look like below so that it will do the POST, but it doesn't seem to work (a GET call is still being made).
sync: function(method, model, options) {
if (method === "read") {
method = "create";
}
return Backbone.sync.call(this, method, model, options);
}
And the fetch looks something like this:
var model = new MyModel();
var deferred = model.fetch({
dataType: "jsonp",
data: {
parm1: "somevalue",
parm2: false,
parm3: {
type1: "abc",
type2: "123"
}
}
});
Any ideas on why this would not be working?
Thanks so much!!
You can pass type
as part of the fetch
method options
argument. What will happen is that Backbone will sync
your request as a read
method, which it is, and just before calling jQuery's ajax
method it will override the type
, as you can see in Backbone's source code.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
So your code should look something like that:
var model = new MyModel();
var deferred = model.fetch({
type: "post",
dataType: "jsonp",
data: {
parm1: "somevalue",
parm2: false,
parm3: {
type1: "abc",
type2: "123"
}
}
});
Remember that the options
you pass to the fetch
method are basically jQuery's ajax
options, with the extension of Backbone's options.
You need to set the type
to "post" in the options that are passed to Backbone.sync
. As mentioned in the sync
docs , options
is "success and error callbacks, and all other jQuery request options":
sync: function(method, model, options) {
var opts = options;
if (method === "read") {
method = "create";
opts = $.extend({}, opts, {
type: "post"
});
}
return Backbone.sync.call(this, method, model, opts);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.