INTRO
在将模型发送到web服务之前,我在试图解析模型时遇到了问题。
我有一个REST web服务设置,它工作得很好,我有我的主干设置来解析web服务JSON响应,这也很好。我能够显示JSON对象
问题是,当我尝试删除或更新模型时,主干从不在模型发送回服务器之前解析该模型,而服务器总是收到null。这是我的代码:
教师模型
window.Teacher = Backbone.Model.extend({
urlRoot: "http://localhost:8080/SIMS/resource/teacher",
defaults: {
"id": null,
"Name": "",
"Password": "",
"email": "",
"dob": "",
"type": ""
},
parse: function(response){
console.log("................................. response test.........");
response.id = response.idTeacher;
console.log("..........."+response.name);
console.log("..........."+response.idTeacher);
response.Password = response.password;
response.Name = response.name;
delete response.name;
delete response.password;
delete response.idTeacher;
return response;
} ,
toJSON: function(){
var attrs = _.clone(this.attributes);
attrs.name = attrs.Name;
delete attrs.Name;
attrs.password = attrs.Password;
delete attrs.Password;
attrs.idTeacher = attrs.id;
delete attrs.id;
return attrs;
}
});
window.TeacherCollection = Backbone.Collection.extend({
model: Teacher,
url: "http://localhost:8080/SIMS/resource/teacher",
parse: function(response){
for (var i=0; i<response.length; i++)
{
console.log("...........help");
response[i].id = response[i].idTeacher;
response[i].Password = response[i].password;
response[i].Name = response[i].name;
console.log(".........."+response[i].Name);
delete response[i].name;
delete response[i].password;
delete response[i].idTeacher;
}
return response ;
}
});教师视图:保存函数
saveTeacher: function() {
this.model.set({
Name: $('#Name').val(),
email: $('#email').val(),
Password: $('#Password').val(),
dob: $('#dob').val(),
type: $('#type').val()
});
if (this.model.isNew()) {
var self = this;
app.teacherList.create(this.model, {
success: function() {
app.navigate('admin/teacher/'+self.model.id, false);
}
});
} else {
this.model.save();
}
return false;
},Web
@PUT @Path("{id}")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public void update(Teacher T){
System.out.println("Updating Teacher:" + T.getName());
teacherejb.edit(T);
}问题
由于我有解析函数,所以我现在使用.attributes而不是toJSON(),这很好。
示例:
render: function(eventName) {
$(this.el).html(this.template(this.model.attributes));
return this;
},但是,当尝试在this.model.save函数中调用saveteahcer函数时,在我将它发送到服务器之前,它从不解析它,我不知道如何先解析它,然后再将它发送到服务器。当我调试代码时,web服务总是接收null,如何使我的web服务正确地接收到教师对象?
发布于 2014-03-03 10:29:41
该解析方法在服务器响应之后称为,参见骨干文件
Parsemodel.parse(响应,选项) 每当服务器在获取和保存中返回模型的数据时,都会调用解析。
我建议您在将数据发送到服务器之前使用验证修改/更新数据:
Validatemodel.validate(属性、选项) 此方法未定义,如果您有任何可以在JavaScript中执行的方法,则鼓励您使用自定义验证逻辑覆盖它。默认情况下,在保存之前调用.
https://stackoverflow.com/questions/22143182
复制相似问题