2

我正在将表单数据转换为 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"}
]}

我该如何解决我的问题??

谢谢

4

3 回答 3

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;
};
于 2013-11-09T11:50:02.243 回答
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/

于 2013-11-09T11:43:24.330 回答
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;
};
于 2013-11-09T11:44:13.167 回答