Serialize JavaScript object into JSON string

后端 未结 8 1630
广开言路
广开言路 2020-12-23 15:49

I have this JavaScript prototype:

Utils.MyClass1 = function(id, member) {
this.id = id;
this.member = member;
}

and I create a new object:<

相关标签:
8条回答
  • 2020-12-23 16:40
        function ArrayToObject( arr ) {
        var obj = {};
        for (var i = 0; i < arr.length; ++i){
            var name = arr[i].name;
            var value = arr[i].value;
            obj[name] = arr[i].value;
        }
        return obj;
        }
    
          var form_data = $('#my_form').serializeArray();
                form_data = ArrayToObject( form_data );
                form_data.action = event.target.id;
                form_data.target = event.target.dataset.event;
                console.log( form_data );
                $.post("/api/v1/control/", form_data, function( response ){
                    console.log(response);
                }).done(function( response ) {
                    $('#message_box').html('SUCCESS');
                })
                .fail(function(  ) { $('#message_box').html('FAIL'); })
                .always(function(  ) { /*$('#message_box').html('SUCCESS');*/ });
    
    0 讨论(0)
  • 2020-12-23 16:44

    Well, the type of an element is not standardly serialized, so you should add it manually. For example

    var myobject = new MyClass1("5678999", "text");
    var toJSONobject = { objectType: myobject.constructor, objectProperties: myobject };
    console.log(JSON.stringify(toJSONobject));
    

    Good luck!

    edit: changed typeof to the correct .constructor. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor for more information on the constructor property for Objects.

    0 讨论(0)
提交回复
热议问题