我正在使用 jQuery 来保存我的 javascript 对象的值。我需要从数据库中检索插入对象的 ID。如果 Save 函数在 javascript 对象中,我知道该怎么做(参见下面的代码)。但是,如果 Save 函数不在 javascript 对象中,我该如何设置 ID 变量?
在职的:
Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
self.Save = function() {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: self.Name, SurnName: self.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
self.ID = ID; //set the ID, it works, since I can reference to self
}
});
};
}¨
那么我现在如何实现一个函数(在 Person 类之外!),例如:
SavePerson = function(p) {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
p.ID = ID; //set the ID, it doesn't work, becouse if I call SavePerson repetedly for different objects, a p will not be a correct person.
}
});
};