码迷,mamicode.com
首页 > Web开发 > 详细

使用ajax处理表单提交信息

时间:2018-10-04 23:55:19      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:使用   send   set   formdata   listen   默认   NPU   pos   div   

很直观的需求

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处理表单提交信息

标签:使用   send   set   formdata   listen   默认   NPU   pos   div   

原文地址:https://www.cnblogs.com/weizhibin1996/p/9743768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!