jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用jquery保存javascript对象并从数据库传递ID大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用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",data: JSON.Stringify({ Name: p.Name,SurnName: p.SurName }),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",success: dfd.resolve
    });
return dfd.promise();
};

var p = new $.Person();

$.SavePerson().then(function(result){
    p.ID = result.d.ID;
});

大佬总结

以上是大佬教程为你收集整理的使用jquery保存javascript对象并从数据库传递ID全部内容,希望文章能够帮你解决使用jquery保存javascript对象并从数据库传递ID所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。