当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery异步提交表单实例

jQuery异步提交表单实例

2018年04月28日  | 移动技术网IT编程  | 我要评论

前言:

我们在开发的时候,一定会使用ajax异步提交表单,在这里总结一下:

前提准备:引入脚本

 <!--jquery需要引入的文件-->
  <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.2.1.js"></script>
  <!--ajax提交表单需要引入jquery.form.js-->
  <script type="text/javascript" src="http://malsup.github.io/jquery.form.js"></script>

前台页面:

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>
<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <base href="<%=basepath%>" rel="external nofollow" >
  <title>title</title>
  <!--jquery需要引入的文件-->
  <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.2.1.js"></script>
  <!--ajax提交表单需要引入jquery.form.js-->
  <script type="text/javascript" src="http://malsup.github.io/jquery.form.js"></script>
  <script>
    $(function () {
      //给id为ajaxsubmit的按钮提交表单
      $("#ajaxsubmit").on("click",function () {
        //alert(1);
        $("#ajaxform").ajaxsubmit({
          beforesubmit:function () {
            // alert("我在提交表单之前被调用!");
          },
          success:function (data) {
            //alert("我在提交表单成功之后被调用");
            if (typeof(data) == "string"){
              data = eval( '('+data+')');
              //alert(data); object
               handle(data);
            }else{
              handle(data);
            }
          }
        });
      });
    });
    //处理返回数据
    function handle(data){
      if(data.status == 200){
        alert(data.message);
        //处理逻辑
      }else{
        alert(data.message);
        //处理逻辑
      }
    }
  </script>
</head>
<body>
<form method="post" action="testajax" id="ajaxform">
  姓名:<input type="text" name="name"/><br>
  年龄:<input type="text" name="age"><br>
  性别:男 <input type="radio" value="man" name="sex" checked/> 女 <input type="radio" value="woman" name="sex"/><br/>
  <br><br><br>
  <input type="submit" value="同步提交"/>   <input type="reset" value="重置" />
  <br> <br> <br>
  <input type="button" value="点我ajax提交表单" id="ajaxsubmit"/>  
</form>
</body>
</html>

后台servlet代码:

package cn.cupcat.controller;
import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
public class testajaxcontorller extends httpservlet{
  /**
   * 
   */
  private static final long serialversionuid = 1l;
  @override
  protected void doget(httpservletrequest req, httpservletresponse resp)
      throws servletexception, ioexception {
    system.out.println("进入了doget方法!");
    //调用都dopost方法,get和post做同样处理
    dopost(req, resp);
  }
  @override
  protected void dopost(httpservletrequest req, httpservletresponse resp)
      throws servletexception, ioexception {
    system.out.println("进入了dopost方法!");
    //设置请求编码
    req.setcharacterencoding("utf-8");
    //设置响应编码
    resp.setcharacterencoding("utf-8");
    //得到表单中的name
    string name = req.getparameter("name");
    //得到表单中的age
    string age = req.getparameter("age");
    //得到表单中的sex
    string sex = req.getparameter("sex");
    //输出打印
    system.out.println("name = "+name + " age = " + age +" sex = "+sex);
    string message = "name = "+name + " age = " + age +" sex = "+sex;
    //返回客户端结果
    string result = getresponseresult(200,message);
    //将result返回客户端
    resp.getwriter().print(result);
    //这里可以不用关闭 resp.getwriter()流,由容器负责管理
  }
  //这里为了简单,没有引入处理json的包,这是模拟json数据
  public static string getresponseresult(int status,string message){
    return "{status: "+status+",message: '"+message+"'}";
  }
}

web.xml配置

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="webapp_id" version="3.1">
 <display-name>upload_demo</display-name>
 <!--  测试ajax servlet开始 -->
 <servlet>
    <servlet-name>testajax</servlet-name>
    <servlet-class>cn.cupcat.controller.testajaxcontorller</servlet-class>
 </servlet>
 <servlet-mapping>
    <servlet-name>testajax</servlet-name>
    <url-pattern>/testajax</url-pattern>
 </servlet-mapping>
 <!-- 测试ajax servlet结束 -->
 <welcome-file-list>
  <welcome-file></welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
</web-app>

注意:

ajaxsubmit({})的也可以这样设置表单的method、action、表单项

type: 'post', // 提交方式 get/post
 url: 'your url', // 需要提交的 url
 data: {
    'title': title,
    'content': content
  },
 success: function(data) { // data 保存提交后返回的数据,一般为 json 数据
  // 此处可对 data 作相关处理
        alert('提交成功!');
 }

以上所述是小编给大家介绍的jquery异步提交表单实例,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网