gpt4 book ai didi

javascript - 具有主干模型的非 RESTful HTTP POST?

转载 作者:行者123 更新时间:2023-11-29 21:48:12 25 4
gpt4 key购买 nike

我一直在看这个文档:

http://backbonejs.org/#Sync

http://addyosmani.github.io/backbone-fundamentals/#backbones-sync-api

尝试弄清楚如何发出 HTTP POST 请求以获取一些 JSON 数据以加载到我的模型中。遗憾的是,Web 服务不是 RESTful,所以我正在执行 POST 请求,而实际上它应该是 GET 请求。这就是生活......

我最终得到了以下结果,但我不确定这是否是正确的方法,或者是否有更简单的方法,而且因为我没有严格使用 REST 模式,所以我似乎无法找到相关的方法我使用主干模式的服务。

    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;

});

所以这段代码本质上是

  1. 使用 header 信息构建 POST 请求
  2. 提出要求
  3. 如果成功,将 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 - 具有主干模型的非 RESTful HTTP POST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com