菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
0
0

AJax入门案例(代码实现)

原创
05/13 14:22
阅读数 175

AJax工作原理

图片.png

AJax请求的五个步骤

1、创建XMLHttpRequest异步对象
2、设置回调函数
3、使用open方法与服务器建立连接
4、向服务器发送数据
5、在回调函数中针对不同的响应状态进行处理

代码实现

功能需求:

根据用户输入的用户名判断该用户名是否存在(已有用户名存储在数据库中)

代码:

jsp页面

<body>
    <form>
        请输入用户名:<input type="text" id="userName">
        <%-- 提示信息--%>
        <span id="tips"></span>
    </form>
</body>

ServletAjax页面

@WebServlet("/ServletAjax")
public class ServletAjax extends HttpServlet {
    // 调用UserInfoservice中方法
    UserInfoService userInfoService = new UserInfoService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");

        // 获取请求参数
        String userName = req.getParameter("userName");
        // 响应回客户端
        PrintWriter out = resp.getWriter();
		// 如果存在
         if (userInfoService.alreadyExist(userName)) {
            out.print("用户名可用!");
        } else {
            out.print("用户名重复!");
        }
    }
}

UserInfoService中alreadyExist()方法

public boolean alreadyExist(String userName) {
        boolean flag = false;
        UserInfo userInfo = userInfoDao.alreadyExist(userName);
        System.out.println(userInfo);
        if (userInfo == null) {
            flag = true;
        }
        return flag;
    }

jsp页面中script脚本

<script>

        //1.创建XMLHttpRequest对象
        var xmlhttp;
        if (window.XMLHttpRequest) {
            //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
            xmlhttp=new XMLHttpRequest();
        }
        else {
            // IE6, IE5 浏览器执行代码
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        window.onload = function () {
            // 绑定监听离焦事件
            document.getElementById("userName").addEventListener("blur", function () {
                checkName();
            });
        }
		
        function checkName() {
            var name = document.getElementById("userName").value;
            // 调用open方法,设置请求的参数传给ServletAjax
            xmlhttp.open("POST", "ServletAjax?userName=" + name, true);
            xmlhttp.send();
            xmlhttp.onreadystatechange=function () {
                // 就绪
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    // 获取ServletAjax输出文本
                    var returnString = xmlhttp.responseText;
                    // 写入提示框
                    document.getElementById("tips").innerText = returnString;
                }
            }
        }
</script>

效果展示

图片.png

图片.png

图片.png

指定回调函数:即设定onreadystatechange属性

当请求被发送到服务器时,我们需要执行一些基于响应的任务。
​每当 readyState 改变时,就会触发 onreadystatechange 事件。
​readyState 属性存有 XMLHttpRequest 的状态信息。
​下面是 XMLHttpRequest 对象的三个重要的属性:
图片.png

封装增强版

在jsp页面中添加如下代码

<script>
        // 页面加载时,ajax请求servlet获取新闻类别信息
        $(function (){
            // 参数值设置,key, value的形式
            var param = {
                option:"getIt"
            }

            $.ajax({
                // 请求方式get或post
                type:"get",
                // 请求的url地址,对应的ServletNewsType类
                url:"ServletNewsType",
                // 传递的参数
                data:param,
                contentType:"text/html;charset=utf-8",
                // 回调函数三个参数值,mess为响应回来的信息
                success:function(mess, status, xhr) {
                    console.log("执行到newsType.jsp请求ajax");
                    // 接收servlet传回的数据并输出
                    console.log("mess" + mess);
                }
            });
            
            });
    </script>

servlet页面(ServletNewsType类)

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        // 获取jsp页面ajax传递过来的option的值
        String option = request.getParameter("option");
        if ("getIt".equals(option)) {
        	getIt(request, response);
        }
    }
// getIt()方法
protected void getIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String mess = "获取到ServletNewsType中的值了";
        // 设置响应格式
        response.setContentType("application/json;charset=utf-8");
        // 创建Gson对象
        Gson gson = new Gson();
        String gsonMess = gson.toJson(mess);
        // 将mess数据传回jsp页面
        response.getWriter().print(gsonMess);
    }

测试结果

启动tomcat点击页面打开控制台,从ajax响应再到ajax接收

发表评论

0/200
0 点赞
0 评论
收藏