Jquery ajax 表单验证

jQuery异步请求大家都很熟悉,这里不再解释。直接上代码

jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘ajax_form.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <!-- 引入jquery -->
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        $(function(){
            //alert($(‘#p‘).html());弹出具体的内容:hello
            
        });
        function lost(){
           //alert(‘失去焦点‘);
           //alert($(‘#name‘)[0].value); 获取输入框的值,首先需要的到这个元素,这个元素是jquery对象,需要转为dom对象,使用数组下标的方法
           $.ajax({ 
                url: "FromServlet", 
                type:"post",
                data:"name="+$(#name)[0].value+"&password=123",//向后台传送的数据格式
                dataType:"json",
                success: function(data, textStatus){
                   //alert(data.password);
                   //alert(data.name);
                   //alert(textStatus);
                   $("#td").after("<font color=‘red‘ fontsize=‘5‘>"+data.name+"用户名已经存在!</font>");
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){
                   alert(textStatus);
                }
           });
           
        }
    </script>

  </head>
  
  <body>
    <p id="p">hello</p>
    <form action="">
         <table>
            <tr>
            <td>用户名:</td>
            <td id="td"><input type="text" name="name" onblur="lost()" id="name"/></td>
            <tr>
            <td>&nbsp;</td>
            <td><input type="password" name="password"/></td>
            </tr>
            <tr>
            <td><input type="submit" value="提交"/></td>
            <td><input type="reset" value="重置"/></td>
            </tr>
         </table>
    </form>
  </body>
</html>

servlet后台代码;

package ajaxServlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class FromServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public FromServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println("你输入的是="+name);
        System.out.println("你输入的密码是="+password);
        PrintWriter out = response.getWriter();
        //String json = "{\"success\":\"你好\",\"type\":\"succ\"}";
        //out.println(json);
        //JSON对象 使用这种方法不用拼装json格式就可以自动转为json数据,不过要导入相应的jar文件,共六个
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("password", password).accumulate("name", name);
        response.setContentType("application/json");
        response.getWriter().write(jsonObject.toString());
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。