我一直在查看此文档:
http://addyosmani.github.io/backbone-fundamentals/#backbones-sync-api
尝试弄清楚如何发出 HTTP POST 请求来获取一些 JSON 数据以加载到我的模型中。遗憾的是,Web 服务不是 RESTful,因此我正在执行 POST 请求,而实际上它应该是 GET 请求。生活就是这样……
我最终得到了以下结果,但我不确定这是否是正确的方法,或者是否有更简单的方法,而且因为我没有严格使用 REST 模式,所以我似乎找不到任何联系我的服务采用 Backbone 模式。
define([
'underscore',
'backbone',
], function (_, Backbone)
{
'use strict';
//model class declaration
var LocationsModel = Backbone.Model.extend({
locations : null, //this stores the json data of buildings and locations
//url for http post to get location data
url: '/locations',
//http request settings
requestType: 'POST',
requestContent : 'application/json; charset=utf-8',
requestBody: { "lastRefreshedDateTime": "2015-04-01T08:18:06.000+00:00", "uid": "12356789" },
requestData: 'json',
/**
@name constructor
@method initialise
**/
initialize: function (xhr)
{
this.doPOST();
},
/**
@name doPOST
@method doPOST
@summary uses AJAX HTTP POST to fetch data from EAS
**/
doPOST: function ()
{
$.ajax({
type: this.requestType,
data: this.requestBody,
contentType: this.requestContent,
dataType: this.requestData,
url: "http://" + window.location.host + this.url,
success: function (result)
{
this.locations = result;
},
error: function (jqXHR, textStatus, errorThrown)
{
//TODO - load cached JSON of buildings and locations
},
});
}
});
return LocationsModel;
});
所以这段代码本质上是
- 使用 header 信息构建 POST 请求
- 提出请求
- 如果成功,请将 JSON 响应加载到模型中
我是否可以对此进行更多抽象?
最佳答案
覆盖.fetch()
:
var RestlessModel = Backbone.Model.extend({
defaults: function(){
return {
locations: []
}
},
//url for http post to get location data
url: '/locations',
//http request settings
fetchOverride: {
type: 'POST',
contentType : 'application/json; charset=utf-8',
data: JSON.stringify({ "lastRefreshedDateTime": "2015-04-01T08:18:06.000+00:00", "uid": "12356789" }),
dataType: 'json',
},
fetch: function(options){
options = _.extend(options || {}, this.fetchOverride);
Backbone.Model.prototype.fetch.call(this, options);
}
});
See fiddle ^^
如果您需要处理请求响应,请覆盖.parse()
。
关于javascript - 具有 Backbone 模型的非 RESTful HTTP POST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373315/