我正在尝试通过我的 View 中的“signIn”功能在我的用户模型上设置数据:
initialize: function() {
console.log('Sign in view initialized');
this.render();
this.userModel = new UserModel();
this.collection = new UserCollection();
},
signIn: function(e) {
e.preventDefault();
var self = this;
$.ajax({
type: 'POST',
url: 'http://localhost/app/api/User.php',
dataType: "json",
data: $.param({
req: "REQUSERSIGNIN",
platform: "WEB",
useremail: $('#userSignIn #userEmail').val(),
userpass: $('#userSignIn #userPassword').val()
}),
success: function(response) {
self.userModel.set({
handle: response.HANDLE,
email: response.EMAIL,
uuid: response.UUIDUSER,
userpic: response.USERPIC,
tokenlogin: response.TOKENLOGIN
});
console.log(self.userModel.get("tokenlogin"));
}
});
},
我读到 .fetch() 或 .save() 是做事的主要方式,但当我使用 fetch 时,我似乎无法设置我的 UserModel。当我以 jQuery.ajax() 方式执行此操作时,它会按预期运行。
有人可以向我解释一下在 $.ajax() 中执行此操作还是通过 .fetch 等执行此操作之间的区别
编辑:
这是我的模型代码
var UserModel = Backbone.Model.extend({
defaults: {
handle: '',
email: '',
uuid: '',
userpic: '',
tokenlogin: ''
},
});
最佳答案
您应该能够通过重写模型的 fetch
方法来做到这一点:
UserModel = Backbone.model.extend({
defaults: {
// ....
},
// set url for model (assumes app root is http://localhost/app)
url: '/api/User.php',
// pass custom parameters on fetch
fetch: function (options) {
var options = _.clone(options);
// set our custom parameters
options.req = "REQUSERSIGNIN";
options.platform = "WEB";
options.useremail = $('#userSignIn #userEmail').val();
options.userpass = $('#userSignIn #userPassword').val();
// call the Backbone method, which in turn calls $.ajax
Backbone.sync.apply(this, options);
},
});
您的模型的 Parse 方法应该可以很好地处理来自服务器的响应,因为看起来是一对一的(response.handle 将匹配 model.attributes.handle)。如果没有看到实际的响应,就很难知道。
关于javascript - $.ajax() 和 Backbone 的 .fetch() 或 .save() 函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18882196/