FormData
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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本