gpt4 book ai didi

javascript - 使用 jquery 保存 javascript 对象并从数据库传递 ID

转载 作者:搜寻专家 更新时间:2023-11-01 04:38:31 26 4
gpt4 key购买 nike

我正在使用 jQuery 来保存我的 javascript 对象的值。我需要从数据库中检索插入对象的 ID。如果 Save 函数在 javascript 对象中(请参见下面的代码),我知道该怎么做。但是,如果保存函数不在 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.
}
});
};

最佳答案

澄清一下,您希望 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;
});

关于javascript - 使用 jquery 保存 javascript 对象并从数据库传递 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10010733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com