Html 访问 FormData 值

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

Accessing FormData Values

javascripthtmlform-data

提问by StuStirling

I have a FormData object which I create in javascriptfrom an HTMLform like so. The FormDataobject doesn't seem very well documented (it may just be me searching the wrong things!).

我有一个 FormData 对象,它是javascript从这样的HTML表单中创建的。该FormData对象似乎没有很好的记录(可能只是我搜索了错误的东西!)。

var form = new FormData(document.getElementById("form"));

My Question

我的问题

How do I access the different input values of this FormDataobject before I send it off? Eg. form.nameaccesses the value that was entered into the input with the name form.name.

如何FormData在发送之前访问此对象的不同输入值?例如。form.name访问以 name 输入到输入中的值form.name

采纳答案by Praveen

It seems you can't get values of the form element using FormData.

似乎您无法使用FormData.

The FormDataobject lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".

FormData对象允许您编译一组键/值对以使用 XMLHttpRequest 发送。它主要用于发送表单数据,但可以独立于表单使用以传输密钥数据。如果表单的编码类型设置为“multipart/form-data”,则传输的数据与表单的 submit() 方法用于发送数据的格式相同。

However you can achieve it using simple Javascript like this

但是,您可以使用像这样的简单 Javascript 来实现它

var formElements = document.forms['myform'].elements['inputTypeName'].value;

回答by Jeff Daze

First thing I don't think it's possible to build a FormData object from a form as you've specified, and to get values from the form use the method described in the accepted answer -- this is more of an addendum!

首先,我认为不可能从您指定的表单构建 FormData 对象,并使用已接受的答案中描述的方法从表单中获取值——这更像是一个附录!

It looks like you canget some data out of a FormData object:

看起来您可以从 FormData 对象中获取一些数据:

var formData = new FormData();
formData.append("email", "[email protected]");
formData.append("email", "[email protected]");
formData.get("email");

Unfortunately, this will only return the firstitem for that key, in this case it will return '[email protected]'

不幸的是,这只会返回该键的第一项,在这种情况下它将返回“[email protected]

Please see also: MDN article on formdata get method.

另请参阅:关于 formdata get 方法的 MDN 文章

回答by carpeliam

FormData.getwill do what you want in a small subset of browsers - look at the browser compatibility chart to see which ones (currently only Chrome 50+ and Firefox 39+). Given this form:

FormData.get将在一小部分浏览器中执行您想要的操作 - 查看浏览器兼容性图表以查看哪些(目前只有 Chrome 50+ 和 Firefox 39+)。鉴于这种形式:

<form id="form">
  <input name="inputTypeName">
</form>

You can access the value of that input via

您可以通过访问该输入的值

var form = new FormData(document.getElementById("form"));
var inputValue = form.get("inputTypeName");

回答by Oculus Hut

Just to add to the previous solution from @Jeff Daze - you can use the FormData.getAll("key name")function to retrieve all of the data from the object.

只是添加到@Jeff Daze 的先前解决方案中 - 您可以使用该FormData.getAll("key name")函数从对象中检索所有数据。

回答by Juschel

This is a solution to retrieve the key-value pairs from the FormData:

这是从 FormData 检索键值对的解决方案:

var data = new FormData( document.getElementById('form') );
data = data.entries();              
var obj = data.next();
var retrieved = {};             
while(undefined !== obj.value) {    
    retrieved[obj.value[0]] = obj.value[1];
    obj = data.next();
}
console.log('retrieved: ',retrieved);

回答by gpaulini

According to MDN:

根据MDN

An object implementing FormData can directly be used in a for...of structure, instead of entries(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries())

实现 FormData 的对象可以直接用于 for...of 结构,而不是 entry(): for (var p of myFormData) 等价于 for (var p of myFormData.entries())

Therefore you can access FormData values like that:

因此,您可以像这样访问 FormData 值:

var formData = new FormData(myForm);

for (var p of formData) {
    let name = p[0];
    let value = p[1];

    console.log(name, value)
}

回答by Selva Ganapathi

it will work

它会工作

let form = document.querySelector("form");
let data = new FormData(form)
formObj = {};
for (var pair of data.entries()) {
  formObj[pair[0]] = pair[1]
}
console.log(formObj)

回答by kxo

A simple HTML5 way (form to object) using the runarberg/formsquarelibrary (npm i --save formsquare):

使用runarberg/formsquare库 ( npm i --save formsquare)的简单 HTML5 方式(从表单到对象):

import formsquare from "formsquare";

const valuesObject = formsquare.filter((el) => !el.disabled).parse(document.getElementById('myForm'));
//=> {"foo": "bar"}

https://github.com/runarberg/formsquare

https://github.com/runarberg/formsquare

回答by Pedro JR

If what you're trying to do is get the content of the FormData or append to it, this is what you should use:

如果您想要做的是获取 FormData 的内容或附加到它,这就是您应该使用的:

Let's say you want to upload an image like so:

假设您想像这样上传图像:

<input type="file" name="image data" onChange={e => 
uploadPic(e)} />

On change handler function:

关于更改处理程序函数:

const handleChange = e => {
    // Create a test FormData object since that's what is needed to save image in server

   let formData = new FormData();

    //adds data to the form object

    formData.append('imageName', new Date.now());
    formData.append('imageData', e.target.files[0]);

}

append: adds an entry to the creates formData object where imageData is the key and e.target.files[0] is the property

append:向创建的 formData 对象添加一个条目,其中 imageData 是键, e.target.files[0] 是属性

You can now send this imageData object which contains data of the image to your server for processing

您现在可以将此包含图像数据的 imageData 对象发送到您的服务器进行处理

but to confirm if this formData has values a simple console.log(formData)/won't do it, what you should do is this:

但是要确认这个 formData 是否有一个简单的 console.log(formData)/ 不会这样做,你应该做的是:

//don't forget to add this code to your on change handler 
function
for (var value of formData.values()) {
   console.log(value); 
}

//I hope that explains my answer, it works for vanilla JavaScript and React.js...thanks in advance for your upvote

//我希望这能解释我的答案,它适用于 vanilla JavaScript 和 React.js...提前感谢您的投票

回答by SandroMarques

My solution with for-of

我的解决方案 for-of

const formData = new FormData(document.getElementById('form'))

for (const [key, value] of formData) {
  console.log('?', key, value)
}