How to get form data as a object in jquery

This question already has an answer here:

  • Convert form data to JavaScript object with jQuery 50 answers

  • Have you tried "serializeArray"? That gives you an array of names and values. You could turn that into an object if you wanted to:

    var paramObj = {};
    $.each($('#myForm').serializeArray(), function(_, kv) {
      paramObj[kv.name] = kv.value;
    });
    

    (I'll have to check again to see what jQuery does with arrays; I think it encodes them as Javascript array values, but I'm not 100% sure.)

    edit ah no, it doesn't set up multi-valued parameters as arrays - you get repeats of the same name. Thus, the make-an-object code should look like this:

    var paramObj = {};
    $.each($('#myForm').serializeArray(), function(_, kv) {
      if (paramObj.hasOwnProperty(kv.name)) {
        paramObj[kv.name] = $.makeArray(paramObj[kv.name]);
        paramObj[kv.name].push(kv.value);
      }
      else {
        paramObj[kv.name] = kv.value;
      }
    });
    

    (or something like that; could probably be squeezed a little.)


    你可以看看serializeArray函数:

    $('#form_id').serializeArray()
    
    链接地址: http://www.djcxy.com/p/46328.html

    上一篇: 将表单数据转换为JSON对象

    下一篇: 如何获取表单数据作为jQuery中的对象