欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用jquery中封装的$.Ajax()进行异步通信

程序员文章站 2022-07-12 19:18:55
...

客户端代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="#" method="post">
    用户名: <input type="text" name="username" id="username" onblur="onChang()">
    <span id="spanUser"></span>
</form>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath}/ajax/jquery/jquery-1.12.4.js"></script>
<%--<script src="jquery\jquery-1.12.4.js"></script>--%>
<script>
    var xml=null;
    function onChang() {
        var username=$("#username").val();
        if (username=="") {
            $("#spanUser").html("<font color='red'>用户名不可以为空</font>")
        }
        else {
            $.ajax(
                {
                    //服务器路径
                    url:"/java92web/checkServlet",
                    //提交方式
                    type:"post",
                    //参数
                    data:"name="+username,
                    //结果返回的形式
                    dataType:"text",
                    //成功后返回的结果
                    success:function (result1) {
                        if (result1=="ok") {
                            $("#spanUser").html("<font color='red'>用户名已占用</font>")
                        }else
                        {
                            $("#spanUser").html("<font color='green'>√</font>")
                        }

                    },
                    //失败的情况
                    error:function () {
                        alert("请联系管理员");

                    }
                }
            )
        }
    }

</script>
</html>

服务器

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/checkServlet")
public class checkServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String name=request.getParameter("name");
        if (name.equals("admin")) {
            out.print("ok");
        }
        else {
            out.print("filed");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}