美文网首页NodeJs
formData提交表单

formData提交表单

作者: 简小园 | 来源:发表于2019-06-28 19:39 被阅读0次
    用form标签
    <body>
      <form id="form1" action="http://localhost:8080/" method="post">
        用户:<input type="text" name="user" /><br>
        密码:<input type="password" name="pass" /><br>
        文件:<input type="file" name="f1" /><br>
        <input type="submit" value="提交">
      </form>
    </body>
    <script src="jquery.js" charset="utf-8"></script>
    <script>
    $('#form1').on('submit', function (){
      let formdata=new FormData(this);   // 通过这个表单构建FormData
      // 发送ajax请求(jQuery的ajax)
      $.ajax({
        url: this.action,
        type: this.method,
        data: formdata,
        processData: false,   // 阻止jQuery处理数据
        contentType: false   // 阻止修改contentType
      }).then(res=>{
        alert('成功');
      }, res=>{
        alert('失败');
      });
    
      return false;    // 阻止表单自己提交
    });
    </script>
    

    同时后台服务器处理提交的数据,用multiparty

    不用form标签
    <body>
      <div id="div1">
        用户:<input type="text" id="user" /><br>
        密码:<input type="password" id="pass" /><br>
        文件:<input type="file" id="f1" /><br>
        <input id="btn1" type="button" value="提交">
      </div>
    </body>
    <script>
    let oBtn=document.querySelector('#btn1');
    oBtn.onclick=function (){
      // 创建FormData
      let formdata=new FormData();
      // 给表单添加页面输入的值
      formdata.append('username', document.querySelector('#user').value);
      formdata.append('password', document.querySelector('#pass').value);
      formdata.append('f1', document.querySelector('#f1').files[0]);
    
      // 发送ajax请求(原生的ajax)
      let xhr=new XMLHttpRequest();
    
      xhr.open('post', 'http://localhost:8080/', true);
      xhr.send(formdata);
    
      xhr.onreadystatechange=function (){
        if(xhr.readyState==4){
          if(xhr.status==200){
            alert('成功');
          }else{
            alert('失败');
          }
        }
      };
    };
    </script>
    

    同时后台服务器处理提交的数据,用multiparty

    后台
    const http=require('http');
    const multiparty=require('multiparty');
    
    http.createServer((req, res)=>{
      let form=new multiparty.Form({
        uploadDir: './upload/'     // 上传到同级目录下的upload文件夹
      });
      form.parse(req);
      // 普通数据
      form.on('field', (name, value)=>{
        console.log('field:', name, value);
      });
      // 文件数据
      form.on('file', (name, file)=>{
        console.log('file:', name, file);
      });
      // 解析结束
      form.on('close', ()=>{
        console.log('完事儿');
      });
    }).listen(8080);
    

    相关文章

      网友评论

        本文标题:formData提交表单

        本文链接:https://www.haomeiwen.com/subject/wuvhcctx.html