FormData
使用Ajax提交表单
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>FormData</title> </head> <body> <form id="login" action="https://www.imooc.com/api/http/search/suggest?words=js" method="post" enctype="application/x-www-form-urlencoded"> <input type="text" name="username" placeholder="用户名" /> <input type="password" name="password" placeholder="密码" /> <input id="submit" type="submit" value="提交" /> </form> <script> //1.使用Ajax提交表单 //2.FormDate的基本用法 //通过HTML表单元素创建FormDate对象 //const fd = new FormData(表单元素); //data.append('age',18); //data.append('sex','male'); //xhr.send(fd); //通过append()方法添加数据 const login = document.getElementById('login'); //console.log(login.username); //console.log(login.password); const { username, password } = login; const btn = document.getElementById('submit'); const url = 'https://www.imooc.com/api/http/search/suggest?words=js' btn.addEventListener( 'click', e => { //阻止表单自动提交 e.preventDefault(); //表单数据验证 //发生Ajax请求 const url = 'https://www.imooc.com/api/http/search/suggest?words=js'; const xhr = new XMLHttpRequest(); xhr.addEventListener('load', () => { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { console.log(xhr.response); } }, false ); xhr.open('POST', url, true); //组装数据 //const data = 'username=${username.value}&password=${passwrod.value}'; const data = new FormData(login); data.append('age',18); data.append('sex','male'); //console.log(data); /* for(const item of data){ console.log(item); } */ // xhr.setRequestHeader( // 'Content-Type', // 'application/x-www-form-urlencoded' // ); xhr.send(data); //xhr.send('username=lyw&passwrod=12345') }, false ); </script> </body> </html>
标签:const,FormData,表单,xhr,login,data From: https://www.cnblogs.com/yu3304/p/17269541.html