Javascript 如何在jquery中将表单数据作为对象获取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2403179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:09:36  来源:igfitidea点击:

How to get form data as a object in jquery

javascriptjquery

提问by kevin

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?

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

回答by Pointy

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

你试过“serializeArray”吗?这为您提供了一组名称和值。如果你想,你可以把它变成一个对象:

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 thinkit encodes them as Javascript array values, but I'm not 100% sure.)

(我将不得不再次检查以查看 jQuery 对数组做了什么;我认为它将它们编码为 Javascript 数组值,但我不是 100% 确定。)

editah 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:

编辑啊不,它不会将多值参数设置为数组 - 你会得到同名的重复。因此,make-an-object 代码应该如下所示:

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

(或类似的东西;可能会被挤压一点。)

回答by Darin Dimitrov

You may take a look at the serializeArrayfunction:

你可以看看serializeArray函数:

$('#form_id').serializeArray()