如何设置Backbone.js的,包括在JSON后的型号名称? [英] How to set Backbone.js to include model name in JSON post?

查看:254
本文介绍了如何设置Backbone.js的,包括在JSON后的型号名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在该同步到谷歌一个App Engine的REST服务器我也把一个项目Backbone.js的。我使用AppEngine上-休息-Server工程code启用REST接口。它的作品真的很好,但有一个问题。当我发布一个新模式,它需要一个JSON帖子的形式:

I've been working on a Backbone.js project that syncs to a Google App Engine REST server I've also put together. I'm using the Appengine-Rest-Server project code to enable the REST interface. IT works really well, but there is one problem. When I post a new model to it, it expects a JSON post in the form of:

{ 'modelname' : {'attribute1':'attribute','attribute2':'attribute'}}

当我使用Python和请求库这个POST数据到我的REST服务器...它工作正常。

When I use python and the requests library to POST this data to my REST server... it works fine.

Backbone.js的出现没有的型号名称要发送POST请求一拉

Backbone.js appears to be sending POST requests without the model name a la

{'attribute1':'attribute','attribute2':'attribute'}

现在,不是一个专家是什么格式是100%基于REST的,我不知道我的REST服务器是否正确配置(在这种情况下,我不希望你们能帮助以code),Backbone.js的是否配置不当,或两种格式是否有潜在的REST风格的,我只是需要弄清楚如何让骨干型号名称中添加。

Now, not being an expert on what formats are 100% RESTful, I'm not sure whether my REST server is improperly configured (in which case I don't expect you guys to be able to help with the code), whether Backbone.js is improperly configured, or whether both formats are potentially RESTful and I just need to figure out how to get backbone to add in the model name.

所以,关门,是一个或一个真正的RESTful API,这两种格式的兼容?如果JSON需要的型号名称不是严重违反作出REST的API,,没有人知道我怎样才能使骨干以正确的格式发送POST请求?

So, to close, is one or both of these formats compatible with a truly RESTful API? If requiring the model name in the JSON is not a gross violation of making a RESTful API, does anyone know how I can make Backbone send out post requests in the proper format?

谢谢!

推荐答案

最优雅的方式:

YourModel = Backbone.Model.extend({

   name: 'modelName',

   toJSON: function () {
       var data = {};

       data[this.name] = _.clone(this.attributes); // or Backbone.Model.prototype.toJSON.apply(this)

       return data;
   }

});

或者你也可以直接将数据传递给的选项

Or you can directly pass data to the options

model.save(null, {
    data: {
       // custom format
    }
});

这篇关于如何设置Backbone.js的,包括在JSON后的型号名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆