更改表单数据的json字符串

时间:2013-11-09 11:34:48

标签: javascript jquery json

我正在处理将表单数据转换为json数据。这是我的代码:

  $.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
                o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';

        }
    });
    return o;
};

$(function() {
    $('form').submit(function() {

        $('#result').append(JSON.stringify($('form').serializeObject()));

        return false;
    });
});

上面的代码给出了以下json字符串:

  {"TypeName":["type1","type2"],"rate":["23","24"],"no:ofTickets":["23","24"],"allowedMembers": ["member1","member2"]}   

但我的需要是让json像这样:

   {[
    {"TypeName":"type1","rate":"23","no:ofTickets":"23","allowedMembers":"member1"},
    {"TypeName":"type2","rate":"34","no:ofTickets":"56","allowedMembers":"member2"}
]}

我怎样才能解决我的问题?

由于

3 个答案:

答案 0 :(得分:1)

serializeArray已经完全相同,您只需将数据转换为所需的格式:

$.fn.serializeObject = function()
{
  var o = {};
  var a = this.serializeArray();
   $.each(a, function()
   {
     if (o[this.name] !== undefined)
     {
        if (!o[this.name].push) 
        {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    }
    else 
    {
        o[this.name] = this.value || '';
    }
 });
 return o;
};

答案 1 :(得分:0)

$.fn.serializeObject = function()
{
    var elements = []; // Define an empty array
    var o = {};
    var a = this.serializeArray();

    $.each(a, function() {
       ...

       elements.push(o); // Store your objects into the array
    });

    return elements; // return the array
}

工作示例http://fiddle.jshell.net/f8Zkr/

答案 2 :(得分:0)

将searialzieObject函数更改为: -

$.fn.serializeObject = function()
{
    var o = [];
    var a = this.serializeArray();
    $.each(a, function() {
        var new_dict = {};   
        if (new_dict[this.name] !== undefined) {
            if (!new_dict[this.name].push) {
                new_dict[this.name] = [new_dict[this.name]];
            }
                new_dict[this.name].push(this.value || '');
        } else {
            new_dict[this.name] = this.value || '';

        }
        o.push(new_dict);
    });
    return o;
};