【发布时间】:2013-01-23 00:34:30
【问题描述】:
我正在开发一个 Web 应用程序,该应用程序由使用 Python 的 CherryPy 框架编写的 restful API 提供支持。我开始使用 jQuery 和服务器端模板的组合来编写用户界面,但最终切换到 Backbone.js,因为 jQuery 失控了。
很遗憾,我在让模型与服务器同步时遇到了一些问题。这是我的代码中的一个简单示例:
$(function() {
var User = Backbone.Model.extend({
defaults: {
id: null,
username: null,
token: null,
token_expires: null,
created: null
},
url: function() {
return '/api/users';
},
parse: function(response, options) {
console.log(response.id);
console.log(response.username);
console.log(response.token);
console.log(response.created);
return response;
}
});
var u = new User();
u.save({'username':'asdf', 'token':'asdf'}, {
wait: true,
success: function(model, response) {
console.log(model.get('id'));
console.log(model.get('username'));
console.log(model.get('token'));
console.log(model.get('created'));
}
});
});
您可能会说,这里的想法是向该服务注册一个新用户。当我调用u.save(); 时,Backbone 确实向服务器发送了一个 POST 请求。以下是相关位:
请求:
Request URL: http://localhost:8080/api/users
Request Method: POST
Request Body: {"username":"asdf","token":"asdf","id":null,"token_expires":null,"created":null}
回应:
Status Code: HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 109
Response Body: {"username": "asdf", "created": "2013-02-07T13:11:09.811507", "token": null, "id": 14, "token_expires": null}
如您所见,服务器成功处理了请求并返回了id 和created 的值。但是由于某种原因,当我的代码调用console.log(u.id); 时,我得到null,而当我的代码调用console.log(u.created); 时,我得到undefined。
tl;dr:为什么 Backbone.js 在调用 save() 后不持久更改我的对象?
编辑:
我已经修改了上面的代码,以便使用success 回调中的get 函数访问模型属性。这应该可以解决原始代码的任何并发问题。
我还在模型的parse 函数中添加了一些控制台日志记录。奇怪的是,每个都是undefined...这是否意味着 Backbone.js 无法解析我的响应 JSON?
编辑 2: 几天前,我发现这个问题实际上是我添加到每个请求以启用 HTTP 基本身份验证的自定义标头。详情请见this answer。
【问题讨论】:
-
您的代码看起来不错(除了您应该使用
Model.urlRoot而不是Model.url,但这不是问题所在)。您的代码的早期版本存在问题,但您确定当前编辑中的确切代码仍然失败吗?
标签: javascript backbone.js http-headers cherrypy basic-authentication