//FormData对象是XMLHTTPRequest level2新增的类型,它可以自动序列化表单内容,不再需要我们去写序列化表单方法;
FormData()即可以直接把整个表单给它,也可以分别使用append(‘字段’,‘值’)方法给FormData();
现在就结合xhr写一个简单示例,怎么把表单传递给后端
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<title>测试xhr和formdata</title>
</head>
<body>
<div id="regform">
<form id="regniter" name="reg" method="post" action="">
<label>
<div class="inputStyle">
用户名:<input type="text" name="username" value=""/>
</div>
</label>
<label>
<div class="inputStyle">
密 码:<input type="password" name="pwd" value=""/>
</div>
</label>
<label>
<div class="inputStyle">
<input type="button" name="submit1" value="提交"/>
</div>
</label>
</form>
</div>
<script>
let btn=document.getElementsByName("submit1");
btn[0].addEventListener("click",function(){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState===4)
{
try{
if((xhr.status>=200&& xhr.status<300) || xhr.status===304)
{
//获取从后端返回的数据
let dataarr=JSON.parse(xhr.response);
console.log(dataarr);
}else
{
console.log("连接后端不成功:",xhr.status);
}
}catch(ex)
{
xhr.ontimeout=function(){
alert('连接超时');
};
}
}
};
xhr.open("post","regniter.php");
let form1=document.forms[0];
let username=form1.elements['username'].value;
let pwd=form1.elements['pwd'].value;
//设置超时为5秒
xhr.timeout=5000;
//设置重写xhr响应的mime类型,这里是json类型,也可以写成application/json形式
xhr.overrideMimeType("text/json");
if(username!=="" && pwd!=="")
{
let data=new FormData(form1);
xhr.send(data);
/*
这里是单独设置字段/值,效果和上面是一样的
data.append('username')=username;
data.append('pwd)=pwd;
xhr.send(data);
*/
form1.elements['submit1'].disabled=true;
console.log('已经发送');
}
})
</script>
</body>
</html>
//这里是后端处理
if(isset($_POST['username'])&&isset($_POST['pwd']))
{
$regArr=[];
$regArr['username']=$_POST['username'];
$regArr['pwd']=$_POST['pwd'];
//注意:这里不能用return,即使是文本也不能用return,不然前端收到是空白
echo json_encode($regArr);
}else
{
echo 'no';
}