Mat*_*tej 5 javascript ajax jquery class object
我使用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
}
});
};
}¨
Run Code Online (Sandbox Code Playgroud)
那么我现在如何实现一个函数(在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.
}
});
};
Run Code Online (Sandbox Code Playgroud)
澄清一下,您希望使用最近的保存来更新 Person 对象 id 属性吗?如果是这样,下面的脚本就足够了。我使用 deferred 来确保 p.ID 仅在异步请求完成后更新。
$.Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
}
$.SavePerson = function() {
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: dfd.resolve
});
return dfd.promise();
};
var p = new $.Person();
$.SavePerson().then(function(result){
p.ID = result.d.ID;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1600 次 |
| 最近记录: |