【发布时间】:2014-03-03 09:40:19
【问题描述】:
简介
在将模型发送到我的 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;
},
网络服务
@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;
},
但是当尝试在saveteahcer 函数中调用this.model.save 时,它在我将其发送到服务器之前从不解析,我不确定如何先解析它然后将其发送到服务器。当我调试 web 服务总是收到 null 的代码时,如何让我的 web 服务正确接收教师对象?
【问题讨论】:
标签: javascript json web-services rest backbone.js