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

使用jquery中封装的$.Ajax()进行异步通信并使用json方式实现数据传输

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

客户端:

<%@ 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",
                    //参数  以json的方式进行传输;
                    data:{name:username},
                    //结果返回的形式
                    dataType:"json",
                    //成功后返回的结果
                    success:function (result) {
                        if (result.recode==1) {
                            $("#spanUser").html("<font color='red'>"+result.retmsg+"</font>")
                        }else
                        {
                            $("#spanUser").html("<font color='green'>"+result.retmsg+"</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("{\"recode\":1,\"retmsg\":\"已注册\"}");
        }
        else {
            out.print("{\"recode\":2,\"retmsg\":\"可以使用\"}");
        }
    }

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