Javascript 使用 POST 请求获取集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6428823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetch a collection using a POST request?
提问by mike
I have managed to work with REST API's to fetch()
data where the urls contain minimal parameters (and use GET
).
我已经设法使用 REST API 处理fetch()
数据,其中 url 包含最少的参数(并使用GET
)。
How would one retrieve a collection through a POST
request?
如何通过POST
请求检索集合?
回答by Arvid Janson
Also note that fetch supports Jquery.ajax parameters, so you can easily set type = post in the call.
另请注意,fetch 支持 Jquery.ajax 参数,因此您可以轻松地在调用中设置 type = post。
Messages.fetch({data: {api_key: 'secretkey'}, type: 'POST'});
For more parameters: http://api.jquery.com/jQuery.ajax/
回答by Walter von Entferndt
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);
}
回答by Bill Eisenhauer
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:
您可能需要扩展 Collection 对象来安装您自己的提取约定。这样做时,您可能会提供自己的 fetch 函数。就像是:
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.
这种方法的缺点是您的应用程序中基本上有框架代码,如果框架发生变化,您可能会遇到问题。您最好将此更改划分为一个单独的层,以便使用新的框架版本轻松更新。
回答by Rob Cowie
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
Backbone.sync 是用于通过模型与服务器交互的函数。您可以提供自己的实现,为“读取”方法而不是 GET 发出 POST 请求。见http://documentcloud.github.com/backbone/#Sync