如何从HTML表单中提取数据?

我有一些Javascript代码,可通过XMLHttpRequest从服务器获取表单的HTML,并将其显示在页面上。

我想做的是提取提交表单后将通过POST发送的数据,再通过另一个XHR发送。棘手的一点是,表单里要包含不同类型的不同元素。

有没有一种方法,不必检查表单上的每个元素,只根据类型就可以手动提取数据并将其全部构建为查询字符串?

Is there a way of doing this without having to inspect each element on the form, determine its type, manually extract the data based on the type, and build it all into a query string?

No, there isn't, but there are prewritten libraries that have the code for that already written. e.g. jQuery serialize

Note that if you want to make a POST request, then the data should go in the request body, not the query string.