Form 表单提交知识的总结(全)

原文链接:https://www.jianshu.com/p/b7cd1ae17360

前言: html 中的form元素被称之为表单,form元素中的内容,包含有交互控制元件,其目的是用来向web 服务器提交信息,实现前后端的交互目的。相关基础内容参照form基础知识文档 ,文章将会启动一个node 后台服务器,对前端form 表单的各种场景以及后端对请求结果的响应做一个归纳总结

1. node服务提供请求地址

   我们通过express 来启动后台服务,并且模拟两个后台接口

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

// 处理请求 的content-type 为application/json
app.use(bodyParser.json())

//处理请求的content-type 为application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))
app.get('/user', (req, res) => {
  console.log(req.query)
  res.send('成功接收')
})


app.post('/user', (req, res) => {
  console.log(req.body)
  res.send('成功接收')
})
app.listen(3008, () => {
  console.log('服务启动')
})

2. 普通的form 表单提交

  form 表单通过method 的属性来确定提交给后台的请求方式,两者的基本用法如下

<!-- form 表单post提交,默认会刷新到 action 页面 -->
    <form action="http://localhost:3008/user" method="POST" name="post提交">
      <p>name: <input type="text" name="username"></p>
      <p>password: <input type="password" name="password"></p>
      <input type="submit" value="提交">
    </form>
    
<!-- form 表单get 提交, 默认刷新action 页面 -->
    <form action="http://localhost:3008/user" method="GET" name="get提交">
      <p>name: <input type="text" name="username"></p>
      <p>password: <input type="password" name="password"></p>
      <input type="submit" value="提交">
    </form>

以下几点需要特别注意

  1. form 的提交行为需要通过type=submit实现
  2. form 中的method 属性不指定时, form 默认的提交方式为 get请求。
  3. form 表单的提交后会有默认行为,会跳转刷新到action 的页面
  4. form 表单的提交方式,请求头默认的content-type 为 x-www-form-urlencoded
  5. 当一个form 表单内部,所有的input 中只有一个 type='text' 的时候,enter 键会有默认的提交行为(注意前提条件)。

3. 阻止新页面跳转

从前面可以知道,form 表单的提交会伴随着跳转到action中指定 的url 链接,为了阻止这一行为,可以通过设置一个隐藏的iframe 页面,并将form 的target 属性指向这个iframe,当前页面iframe则不会刷新页面

<!-- 无刷新页面提交 -->
    <form action="http://localhost:3008/user" method="POST" name="post提交" target="targetIfr">
      <p>name: <input type="text" name="username"></p>
      <p>password: <input type="password" name="password"></p>
      <input type="submit" value="提交">
    </form>
    <iframe name="targetIfr" style="display:none"></iframe>

4. 脚本触发form 表单的提交行为

js事件触发表单提交,通过button、链接等触发事件,js调用submit()方法提交表单数据,jquery通过submit()方法

<!-- html -->
<!-- 通过js 进行表单的提交 存在问题,页面会跳转刷新-->
    <form action="http://localhost:3008/user" method="POST" name="jsForm" target="targetIfr" id="jsForm">
      <p>name: <input type="text" name="username"></p>
      <p>password: <input type="password" name="password"></p>
      <button id="btn">提交</button>
    </form>

    <!-- 通过jquery 进行表单的提交 存在问题,并阻止页面跳转刷新-->
    <form action="http://localhost:3008/user" method="POST" name="jqueryForm" target="targetIfr" id="jqueryForm">
      <p>name: <input type="text" name="username"></p>
      <p>password: <input type="password" name="password"></p>
      <button id="jqbtn">提交</button>
    </form>
// js
var btn = document.getElementById('btn')
var jsForm = document.getElementById('jsForm')
btn.onclick = function () {
    jsForm.submit()
}
// jquery
$('#jqbtn').click(function () {
  $('#jqueryForm').submit(function () {
    console.log('submit success')
    return false
  })
})

说明:

  1. 通过脚本提交行为依然存在跳转 新页面刷新的问题
  2. 脚本中可以通过阻止默认行为来禁止页面跳转

5. ajax 提交请求

<!-- ajax 请求 -->
    <form method="POST">
      <p>name: <input type="text" name="username"></p>
      <p>password: <input type="password" name="password"></p>
      <div id="jqbtn">提交</div>
    </form>
 $('#jqbtn').click(function () {
      $.ajax({
        url: 'http://localhost:3008/user',
        type: 'POST',
        data: JSON.stringify(params),
        contentType: "application/json", // 默认以formdata形式发送给后台
        dataType: "json",
        success: function (res) {
          console.log(res)
        }
      })
    })

注意事项:

  1. 通过ajax 请求模拟form 的提交需要注意 form 表单内 不允许 <button type="submit"></button>的存在,否则会和ajax 自身的请求相冲突
  2. ajax 请求中,默认的content-type 为'formdata',可根据自己的需要修改
  3. 后台对不同的content-type 请求头的处理如下
// 处理请求 的content-type 为application/json
app.use(bodyParser.json())

//处理请求的content-type 为application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))
  1. ajax 请求需要处理跨域问题,而form 表单的默认提交不需要,原因是,原页面用form 提交到另一个域名之后,原脚本无法获取响应的内容,所以浏览器认为这是安全的,而ajax 需要处理响应的内容,浏览器则认为这是一种跨域的行为
  2. 为了解决ajax 的跨域问题,需要在后台的代码中加入跨域的处理
const cors = require("cors")
// 解决跨域
app.use(cors())

6. FormData 处理文件的上传

文件的上传,请求头中content-type 的形式需要修改为multipart/form-data, 相应的,只要将form的enctype 属性修改为enctype="multipart/form-data"即可

<!-- FormData -->
    <form action="http://localhost:3008/user" method="POST" enctype="multipart/form-data">
      <p><input type="file" name="file"></p>
      <input type="submit" value="提交">
    </form>

后台处理部分,我们需要额外安装formidable 依赖来解决form-data 格式的解析

const formidable = require('formidable')

const form = new formidable.IncomingForm();

app.post('/user', (req, res) => {
  form.parse(req, function (err, fields, files) {
    console.log(files)
    res.send('成功接收')

  })
})

7.总结

form 表单前后端的处理汇总如上,详细的代码可以参考 github

posted @ 2018-10-17 14:02  不做祖国的韭菜  阅读(788)  评论(0编辑  收藏  举报