如何使用 JavaScript/jQuery 获取表单数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2276463/
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-22 23:35:05  来源:igfitidea点击:

How can I get form data with JavaScript/jQuery?

javascriptjqueryforms

提问by Bart van Heukelom

Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?

是否有一种简单的单行方式来获取表单数据,就像以经典的纯 HTML 方式提交一样?

For example:

例如:

<form>
    <input type="radio" name="foo" value="1" checked="checked" />
    <input type="radio" name="foo" value="0" />
    <input name="bar" value="xxx" />
    <select name="this">
        <option value="hi" selected="selected">Hi</option>
        <option value="ho">Ho</option>
</form>

Output:

输出:

{
    "foo": "1",
    "bar": "xxx",
    "this": "hi"
}

Something like this is too simple, since it does not (correctly) include textareas, selects, radio buttons and checkboxes:

像这样的东西太简单了,因为它没有(正确地)包括文本区域、选择、单选按钮和复选框:

$("#form input").each(function () {
    data[theFieldName] = theFieldValue;
});

回答by Paul

Use $('form').serializeArray(), which returns an array:

使用$('form').serializeArray(),它返回一个数组

[
  {"name":"foo","value":"1"},
  {"name":"bar","value":"xxx"},
  {"name":"this","value":"hi"}
]

Other option is $('form').serialize(), which returns a string:

另一个选项是$('form').serialize(),它返回一个字符串

"foo=1&bar=xxx&this=hi"

Take a look at this jsfiddle demo

看看这个 jsfiddle 演示

回答by chelmertz

$('form').serialize() //this produces: "foo=1&bar=xxx&this=hi"

demo

演示

回答by mikemaccana

Updated answer for 2014:HTML5 FormDatadoes this

2014 年更新答案:HTML5 FormData执行此操作

var formData = new FormData(document.querySelector('form'))

You can then post formData exactly as it is - it contains all names and values used in the form.

然后,您可以完全按原样发布 formData - 它包含表单中使用的所有名称和值。

回答by neuront

Based on jQuery.serializeArray, returns key-value pairs.

基于jQuery.serializeArray,返回键值对。

var data = $('#form').serializeArray().reduce(function(obj, item) {
    obj[item.name] = item.value;
    return obj;
}, {});

回答by Brad

document.querySelector('form').addEventListener('submit', (e) => {
  const formData = new FormData(e.target);
  // Now you can use formData.get('foo'), for example.
  // Don't forget e.preventDefault() if you want to stop normal form .submission
});

This is a nitpicky answer, but let me explain why this is a better solution:

这是一个挑剔的答案,但让我解释一下为什么这是一个更好的解决方案:

  • We're properly handling a form submit rather than a button press. Some people like to push enter on fields. Some people use alternative input devices such as speech input or other accessibility devices. Handle the form submit and you correctly solve it for everyone.

  • We're digging into the form data for the actual form that was submitted. If you change your form selector later, you don't have to change the selectors for all the fields. Furthermore, you might have several forms with the same input names. No need to disambiguate with excessive IDs and what not, just track the inputs based on the form that was submitted. This also enables you to use a single event handler for multiple forms ifthat is appropriate for your situation.

  • The FormData interface is fairly new, but is well supported by browsers. It's a great way to build that data collection to get the real values of what's in the form. Without it, you're going to have to loop through all the elements (such as with form.elements) and figure out what's checked, what isn't, what the values are, etc. Totally possible if you need old browser support, but the FormData interface is simpler.

  • I'm using ES6 here... not a requirement by any means, so change it back to be ES5 compatible if you need old browser support.

  • 我们正在正确处理表单提交而不是按钮按下。有些人喜欢在字段上按回车键。有些人使用替代输入设备,例如语音输入或其他辅助功能设备。处理表单提交,为大家正确解决。

  • 我们正在深入研究提交的实际表单的表单数据。如果您稍后更改表单选择器,则不必更改所有字段的选择器。此外,您可能有多个具有相同输入名称的表单。无需消除过多 ID 的歧义,只需根据提交的表单跟踪输入即可。如果适合您的情况,这也使您能够对多个表单使用单个事件处理程序。

  • FormData 接口相当新,但浏览器支持良好。这是构建数据集合以获取表单中内容的真实值的好方法。没有它,您将不得不遍历所有元素(例如 with form.elements)并找出检查的内容,未检查的内容,值是什么等。如果您需要旧的浏览器支持,则完全有可能,但 FormData界面更简单。

  • 我在这里使用 ES6...无论如何都不是必需的,因此如果您需要旧浏览器支持,请将其改回 ES5 兼容。

回答by Nils

use .serializeArray() to get the data in array format and then convert it into an object:

使用 .serializeArray() 以数组格式获取数据,然后将其转换为对象:

function getFormObj(formId) {
    var formObj = {};
    var inputs = $('#'+formId).serializeArray();
    $.each(inputs, function (i, input) {
        formObj[input.name] = input.value;
    });
    return formObj;
}

回答by Clox

Here's a really simple and short soluton that even doesn't require Jquery.

这是一个非常简单和简短的解决方案,甚至不需要 Jquery。

var formElements=document.getElementById("myForm").elements;    
var postData={};
for (var i=0; i<formElements.length; i++)
    if (formElements[i].type!="submit")//we dont want to include the submit-buttom
        postData[formElements[i].name]=formElements[i].value;

回答by fringd

It is 2019 and there's a better way to do this:

现在是 2019 年,有一个更好的方法来做到这一点:

const form = document.querySelector('form');
const data = new URLSearchParams(new FormData(form).entries());

or if you want a plain Object instead

或者如果你想要一个普通的对象

const form = document.querySelector('form');
const data = Object.fromEntries(new FormData(form).entries());

although note that this won't work with duplicate keys like you get from multi-select and duplicate checkboxes with the same name.

尽管请注意,这不适用于重复键,就像您从具有相同名称的多选和重复复选框中获得的一样。

回答by Andy Baird

$('#myform').serialize();

回答by Dustin Poissant

I use this:

我用这个:

jQuery Plugin

jQuery 插件

(function($){
  $.fn.getFormData = function(){
    var data = {};
    var dataArray = $(this).serializeArray();
    for(var i=0;i<dataArray.length;i++){
      data[dataArray[i].name] = dataArray[i].value;
    }
    return data;
  }
})(jQuery);

HTML Form

HTML 表单

<form id='myform'>
  <input name='myVar1' />
  <input name='myVar2' />
</form>

Get the Data

获取数据

var myData = $("#myForm").getFormData();