当我在客户端执行model.save()时,我在Spring框架控制器中获取null值。如果我使用Jquery ajaxSubmit()接收的值很好,如何使用model.save()实现相同的目标
我的登录模型和客户端代码中的视图(使用了Backbone)
$.ready = function() {
var LoginModel, LoginView;
// Login Model
LoginModel = Backbone.Model.extend({
// URL to authenticate login.
url: 'authenticate',
// Ensure that each todo created has `title`.
initialize: function() {
console.log("LoginModel initialized");
this.bind("change", this.attributesChanged);
},
validate: function(attrs) {
console.log("LoginModel validate");
},
attributesChanged: function(){
console.log("LoginModel attributesChanged");
}
});
// Login View
LoginView = Backbone.View.extend({
el: $('#loginform'),
events: {
"click #login-button": "performLogin",
"change #login-username": "setUsername",
"change #login-password": "setPassword"
},
initialize: function() {
this.username = $("#login-username");
this.password = $("#login-password");
this.loginButton = $("#login-button");
},
setUsername: function(e){
this.model.set({username: this.username.val()});
console.log("LoginView username set = " + this.username.val());
},
setPassword: function(e){
this.model.set({password: this.password.val()});
console.log("LoginView password set = " + this.password.val());
},
performLogin: function(event) {
event.preventDefault();
this.model.save();
return false;
}
});
var loginview = new LoginView({model: new LoginModel()});
}
HTML表单
<form id="loginform" action="authenticate" method="POST">
<div>
User Name
<input name="username" type="text" align="right" id="login-username">
<br/>
<br/>
Password
<input name="password" type="password" align="right" id="login-password">
</div>
<button type="submit" id="login-button">Login</button>
</form>
脚本标记使用$ .ajaxForm
$('#loginform').submit(function() {
$(this).ajaxSubmit();
return false;
});
答案 0 :(得分:0)
您正在使用jQuery form plugin
,我相信它使用JQuery serialize
方法,该方法将表单参数转换为查询字符串:
?username=name&password=pw
与Backbone对比,后者使用toJSON
序列化模型数据:
{ username: name, password: pw }
所以看起来你有两个选择:
sync
(或者序列化/反序列化方法toJSON
和parse
)假设您使用(2),您可以在单个模型中覆盖该方法,或通过修改Backbone.Model
原型全局覆盖:
Backbone.Model.prototype.sync = function(method, model, options) {
if (method == "create" || method == "update") {
var self = this;
// get model in query-string format
var q = _.keys(this.attributes).map(function(prop) {
return prop + '=' + self[prop];
}).join('&');
// Post data to server
$.post(this.url, _.extend(options, { data: q }) );
}
}
答案 1 :(得分:0)
以下代码有效
Backbone.Model.prototype.sync = function(method, model, options) {
if (method == "create" || method == "update") {
var self = this;
var options = {
url: this.url,
type: 'POST',
success: function() {
alert('Thanks for your comment!');
}
};
// submit the form
$(this.el).ajaxSubmit(options);
}
};
在最后一行,我使用了$(this.el),这里'el'表示表单id(选择器)。