如何在jquery中将表单数据作为对象获取 [英] How to get form data as a object in jquery

查看:431
本文介绍了如何在jquery中将表单数据作为对象获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过 jQuery('#form_id')。serialize()。这仅返回表单数据作为url编码的字符串。是否可以将表单数据作为对象?

I have tried jQuery('#form_id').serialize(). This returns only the form data as a url encoded string. Is it possible to get the form data as an object?

推荐答案

您是否尝试过serializeArray?这会为您提供一系列名称和值。如果您愿意,可以将其转换为对象:

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;
});

(我必须再次检查jQuery对数组的作用;我认为它将它们编码为Javascript数组值,但我不是100%肯定。)

(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.)

编辑啊不,它没有不要将多值参数设置为数组 - 您将获得相同名称的重复。因此,make-an-object代码应如下所示:

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.)

这篇关于如何在jquery中将表单数据作为对象获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆