表单同步提交与异步提交

同步提交
<form id="register_form" method="post" action="/register">
      <div class="form-group">
        <label for="email">邮箱</label>
        <input type="email" class="form-control" id="email" name="email" placeholder="Email" autofocus>
      </div>
      <div class="form-group">
        <label for="nickname">昵称</label>
        <input type="text" class="form-control" id="nickname" name="nickname" placeholder="Nickname">
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input type="password" class="form-control" id="password" name="password" placeholder="Password">
      </div>
      <button type="submit" class="btn btn-success btn-block">注册</button>
    </form>

表单具有默认的提交行为,默认是同步的,同步表单提交,浏览器会锁死(转圈儿)等待服务端的响应结果。
表单的同步提交之后,无论服务端响应的是什么,都会直接把响应的结果覆盖掉当前页面。(服务器重定向只针对同步提交有效)

异步提交(ajax)
$('#register_form').on('submit', function (e) {
    e.preventDefault()
    let formData = $(this).serialize()
     //console.log(formData)
    $.ajax({
      url: '/register',
      type: 'post',
      data: formData,
      dataType: 'json',
      success: function (data) {
        const err_code = data.err_code
          console.log(err_code)
        if (err_code === 0) {
           //window.alert('注册成功!')
          // 服务端重定向针对异步请求无效
          window.location.href = '/'
        } else if (err_code === 1) {
            window.alert('邮箱或昵称已存在!')
            }
        else if (err_code === 500) {
          window.alert('服务器忙,请稍后重试!')
      }
      }
    })
  })

在进行表单异步提交时,服务器重定向是无效的。这时,需要在客户端进行路由跳转。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值