三种方法:
- formData: form.onsubmit中 new FormData(formElement)
- form.elements 遍历,利用e.type判断类型再获取e.name,e.value
- Vue 通过v-model表单输入绑定
html
<form id="form" method="post">
<select id="select1" name="select">
<option value="" disabled selected>--请选择--</option>
<option value="1">--1--</option>
<option value="2">--2--</option>
<option value="3">--3--</option>
</select>
<input id="radio1" type="radio" name="sex" value="female" />female
<input id="radio2" type="radio" name="sex" value="male" />male
<input id="text1" type="text" name="text" />
<fieldset>
<legend>请做出选择:(多选)</legend>
<input type="checkbox" name="checkbox" value="A" />A
<input type="checkbox" name="checkbox" value="B" />B
<input type="checkbox" name="checkbox" value="C" />C
</fieldset>
<input type="submit" value="提交" />
</form>
let serialNumber = 0
const formElement = document.querySelector("#form")
formElement.onsubmit = getFormData
function getFormData(e) {
let formData = new FormData(formElement)
formData.append("serialNumber", ++serialNumber)
for ([name, value] of formData.entries()) {
console.log(`${name}:${value}`)
}
/* 手动发送数据 xhr */
// var request = new XMLHttpRequest()
// request.open("POST", "submitform.php")
// request.send(formData)
e.preventDefault()
}
const formElement = document.querySelector("#form")
formElement.onsubmit = getFormData
function getFormData(e) {
let res = []
Array.prototype.forEach.call(form.elements, (e) => {
console.log(e.type, e.name, e.value) //e.nodeType是判断元素节点 文本节点 注释节点 属性节点的。
switch (e.type) {
case "select-one": // select控件的类型是 select-one
case "text":
case "textarea":
res.push([e.name, e.value])
break
case "checkbox":
case "radio":
if (e.checked) {
res.push([e.name, e.value])
}
break
default:
// 其他的控件 如 button fieldset等 什么也不做
break
}
})
console.log(res)
e.preventDefault()
}