Jquery ajax 表单验证处理返回的xml格式数据

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($("#name").val());
           //alert('失去焦点');
           //alert($('#name')[0].value); 获取输入框的值,首先需要的到这个元素,
           //这个元素是jquery对象,需要转为dom对象,使用数组下标的方法.也可以使用 alert($("#name").val());
           $.ajax({ 
                url: "FromServlet", 
                type:"post",
                data:"name="+$('#name')[0].value+"&password=123",//向后台传送的数据格式
                dataType:"xml",
                success: function(data, textStatus){
                //返回的是json的格式
                   //alert(data.password);
                   //alert(data.name);
                   //alert(textStatus);
                  // $("#td").after("<font color='red' fontsize='5'>"+data.name+"用户名已经存在!</font>");
                  
              //返回的是xml数据格式
                 //需要将data这个dom对象中的数据解析出来
                 //首先需要将dom的对象转换成JQuery的对象
                 var jqueryObj = $(data);
                 //children方法获取的是跟节点下的所有的孩子节点的文本节点(包括直接孩子和间接孩子节点)
                // var childs = jqueryObj.children();  
                 //alert(childs.text());
                 //find方法查找是按照节点的名字来查询的.如果该节点下还有孩子节点,则取到的是孩子节点的文本节点,要和text()方法一起使用
                 var message = jqueryObj.find("name");
                 var message2 = jqueryObj.find("sex");
                 //获取节点的文本内容
                 var text = message.text();
                 var sex = message2.text();
                 alert(text);
                 alert(sex);
                  
                },
                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();
        /**+++++++++++++++++++++json++++++++++++++++++++++++++++++++++++++*/
        //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());*/
        /**+++++++++++++++++++++xml++++++++++++++++++++++++++++++++++++++*/
        out.println("<student>");
        out.println("<name>");
        out.println("<firstName>");
        out.println("wkl");
        out.println("</firstName>");
        out.println("</name>");
        out.println("<sex>");
        out.println("M");
        out.println("</sex>");
        out.println("</student>");
    }

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

}
原文地址:https://www.cnblogs.com/kailing-con/p/4267809.html