JavaScript获取表单数据的方法有以下几种:
document.getElementById()
方法获取表单元素的值。例如:var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
document.forms
属性获取表单元素的值。例如:var username = document.forms["myForm"]["username"].value;
var password = document.forms["myForm"]["password"].value;
document.querySelector()
或document.querySelectorAll()
方法获取表单元素的值。例如:var username = document.querySelector("#username").value;
var password = document.querySelector("#password").value;
document.forms["myForm"].elements
属性获取表单元素的值。例如:var username = document.forms["myForm"].elements["username"].value;
var password = document.forms["myForm"].elements["password"].value;
FormData
对象获取表单数据。例如:var form = document.querySelector("form");
var formData = new FormData(form);
var username = formData.get("username");
var password = formData.get("password");
注意:以上方法中,username
和password
是表单元素的name属性值。