Fetch a collection using a POST request?

徘徊边缘 提交于 2019-11-29 10:50:23

问题


I have managed to work with REST API's to fetch() data where the urls contain minimal parameters (and use GET).

How would one retrieve a collection through a POST request?


回答1:


Also note that fetch supports Jquery.ajax parameters, so you can easily set type = post in the call.

Messages.fetch({data: {api_key: 'secretkey'}, type: 'POST'});

For more parameters: http://api.jquery.com/jQuery.ajax/




回答2:


You may need to extend the Collection object to install your own convention for fetches. In doing so, you would likely provide your own fetch function. Something like:

fetch : function(options) {
  options || (options = {});
  var model = this;
  var success = function(resp) {
    if (!model.set(model.parse(resp), options)) return false;
    if (options.success) options.success(model, resp);
  };
  var error = wrapError(options.error, model, options);
  (this.sync || Backbone.sync)('create', this, success, error);
  return this;
}

where it uses a 'create' instead of a 'read'. On first blush, this is what I'd try first, though there may be a more elegant way to do it.

The downside of this approach is that you essentially have framework code in your app and if the framework changes you might encounter problems. You would do well to compartmentalize this change into a separate layer to make it easy to update with new framework releases.




回答3:


Backbone.sync is the function used to interact with the server via your models. You can provide your own implementation that issues a POST request for the 'read' method instead of GET. See http://documentcloud.github.com/backbone/#Sync




回答4:


try {
    // THIS for POST+JSON
    options.contentType = 'application/json';
    options.type = 'POST';
    options.data = JSON.stringify(options.data);

    // OR THIS for GET+URL-encoded
    //options.data = $.param(_.clone(options.data));

    console.log('.fetch options = ', options);
    collection.fetch(options);
} catch (excp) {
    alert(excp);
}


来源:https://stackoverflow.com/questions/6428823/fetch-a-collection-using-a-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!