• 使用ajax处理表单提交信息


    很直观的需求

    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

  • 相关阅读:
    Attributes in C#
    asp.net C# 时间格式大全
    UVA 10518 How Many Calls?
    UVA 10303 How Many Trees?
    UVA 991 Safe Salutations
    UVA 10862 Connect the Cable Wires
    UVA 10417 Gift Exchanging
    UVA 10229 Modular Fibonacci
    UVA 10079 Pizza Cutting
    UVA 10334 Ray Through Glasses
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9743768.html
Copyright © 2020-2023  润新知