很直观的需求
1、需要在不进行页面跳转的情况下进行表单验证,或者只是单纯的数据上传
2、不使用默认的提交方法,很low!和难受
这是表单
<form id="form"> ?<input type="text" name="user" id="user" placeholder="user"> ?<br> ?<input type="password" name="password" id="password" placeholder="password"> ?<br> ?<input type="file" name="file" id="file"> ?<br> ?<!-- 自带回调函数的,就是会get提交 --> ?<input type="submit" name="submit" id="submit"> ?<!-- 自带回调函数的,就是会重置 --> ?<input type="reset" name="reset" id="reset"></form>
这是脚本
<script type="text/javascript"> ?????var submit = document.getElementById(‘submit‘); ?submit.addEventListener(‘click‘,(e)=>{ ???//这样就能阻止默认的提交事件了 ???e.preventDefault(); ???// var user = document.getElementById(‘user‘); ???// var password = document.getElementById(‘password‘); ???// var file = document.getElementById(‘file‘); ???// // 获取所有的数据 ???// console.log(user.value); ???// console.log(password.value); ???// console.log(file.value); ???//单纯获取value是没有用的,比如只能获取文件名 ???var form = document.getElementById(‘form‘); ???var formData = new FormData(form); ???console.log(formData.get(‘user‘)); ???console.log(formData.get(‘password‘)); ???console.log(formData.get(‘file‘)); ???//使用ajax ???var ajax = new XMLHttpRequest(); ???ajax.open("POST", "/api/xxxxx", true); ???ajax.send(formData); ???ajax.onreadystatechange = ()=>{ ?????//如果成功,进行跳转 ?????setTimeout(()=>{ ???????location.href = ‘https://www.baidu.com‘; ?????},2000); ???}; ?})</script>
总结
1、阻止默认,prevent
2、封装表单数据,使用formdata!不然文件只获取value的话,只有名字。而file应该是一个对象
3、页面跳转location.href
使用ajax处理表单提交信息
原文地址:https://www.cnblogs.com/weizhibin1996/p/9743768.html