使用Backbone模型的非RESTful HTTP POST?

时间:2015-05-21 12:08:46

标签: javascript ajax json backbone.js

我一直在查看此文档:

http://backbonejs.org/#Sync

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;

});

所以这段代码基本上是

  1. 使用标头信息构建POST请求
  2. 提出请求
  3. 如果成功,请将JSON响应加载到模型中
  4. 无论如何我可以抽象更多吗?

1 个答案:

答案 0 :(得分:2)

覆盖.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()