form表单改为AJAX提交

本文介绍如何将传统的form表单提交方式转换为使用AJAX进行异步提交的方法。包括移除form表单的action和method属性,使用JavaScript监听提交按钮点击事件,并通过$.ajax()方法实现数据的异步发送及响应处理。

一、form表单改成AJAX提交

原来的form格式

<form action="xxx" method="get">  //action的值是请求的url地址
    <div class="form-group">
        <label for="name">姓名</label>
        <input type="text" class="form-control" name="name">
    </div>
    <div class="form-group">
        <label for="jobNumber">工号</label>
        <input type="number" class="form-control" name="jobNumber">
    </div>
    <div class="form-group">
        <label for="nation">民族</label>
        <input type="text" class="form-control" name="nation">
    </div>
    <div class="form-group">
        <label for="gender">性别</label>
        <input type="text" class="form-control" name="gender">
    </div>
    <div class="modal-footer">
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   <button type="submit" class="btn btn-primary">提交</button> 
    </div>
</form> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

修改成AJAX提交的流程

  1. 将form元素的属性action和method去掉,添加id=”myForm”,form元素就变为<form id="myForm">

  2. 将提交按钮的button的type=”submit”改为type=”button”,增加 id

  3. 在js文件中写入

 $("#按键的id").click(function () {
    $.ajax({  
            type: "POST",   //提交的方法
            url:"/home/request", //提交的地址  
            data:$('#fm').serialize(),// 序列化表单值  
            async: false,  
            error: function(request) {  //失败的话
                 alert("Connection error");  
            },  
            success: function(data) {  //成功
                 alert(data);  //就将返回的数据显示出来
                 window.location.href="跳转页面"  
            }  
         });
       });  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值