简体   繁体   中英

Methods of javascript object running on jquery ajax call

I have declared a Javascript class in this way:

function MyClass(params){

    this.setValues=function(params){
        this.myAttr1=params.attr1;
        this.myAttr2=params.attr2;
    }
    this.setValues(params);
}

As a result I have MyClass with public attributes myAttr1 , myAttr2 and a public function setValues .

When I do

var myObj=new MyClass({attr1:"hi",attr2:"ho"});

The object is created correctly. The problem comes when I want to send this object as a parameter in a jquery ajax call:

 $.ajax({
            type: "POST",
            url: "insert.php",
            dataType: 'json',
            data: {id: "1", obj:myObj});

At this point I get an error because params in setValues is not defined. So this ajax call is trying to run setValues() (I don't now why).

I found a solution creating a function that return only the attributes inside myClass .

this.getValues=function(){
    return {myAttr1:this.myAttr1,myAttr2:this.myAttr2};
}

And then

$.ajax({
            type: "POST",
            url: "insert.php",
            dataType: 'json',
            data: {id: "1", obj:myObj.getValues()});

But then any time I add an attribute I have to remember to return it in getValues() .
I guess there is a better solution. Maybe I am not following best practices on declaring a class.

Instead of .getValues you should implement a .toJSON function to handle serializing your class to JSON. When your object is stringified (by an underlying call to JSON.stringify), it will automatically call .toJSON .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM