分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

使用ajax处理表单提交信息

发布时间:2023-09-06 02:17责任编辑:郭大石关键词:暂无标签

很直观的需求

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved