Ajax 和 Servlet 联动


在这里插入图片描述

  AJAX, Asynchronous JavaScript and XML。
  通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

  简单封装 Ajax 工具类。


// ajax.js
function getXmlhttpRequset() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {

            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("您的浏览器不支持AJAX!");
                return false;
            }
        }
    }
    return xmlHttp;
}


function ajax(param) {

    // 1.获取xmlHttpRequset
    var xmlHttp = getXmlhttpRequset();

    // 2.设置请求参数
    xmlHttp.open(param.method, param.url);

    // 设置请求头
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    // 3.发送请求
    if (param.method == "POST") {
        xmlHttp.send(param.data);
    } else if (param.method == "GET") {
        xmlHttp.send();
    }

    // 4.监听请求状态
    xmlHttp.onreadystatechange = function () {

        // readyState,Ajax响应状态;status,服务端响应状态。
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

			// 接收 xml 数据。
            console.log("XML: " + xmlHttp.responseXML)

            // 6、调用回调函数
            param.callback(xmlHttp.responseText);
        }
    }
}

  服务端接收数据和响应。(部分代码)


@WebServlet("/AjaxServlet/*")
public class AjaxServlet extends DispacherServlet {

    public void hello(HttpServletRequest request, HttpServletResponse response) {

        // 接收服务端原数据
        try {
            BufferedReader reader = request.getReader();
            System.out.println(reader.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 接收服务端数据,application/x-www-form-urlencoded
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        System.out.println(username + "\t" + age);

        // 响应文本信息到客户端
        try {
        	response.getWriter().write("响应文本。");
            // response.getWriter().write("<html><body><p>Hello</p> <div>Ajax</div></body></html>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  index.jsp。


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>

    <script type="text/javascript" src="js/ajax.js"></script>
    <script type="text/javascript">

      window.onload = function () {
        document.getElementById("button1").addEventListener("click", function () {

          var param = {
            // method: "GET",
            // url:"AjaxServlet/hello?username=zs&age=23",
            method: "POST",
            url:"AjaxServlet/hello",
            data:"username=zs&age=23",
            callback: function (res) {
              console.log(res);
              document.getElementById("div1").innerText = res;
            }
          };

          ajax(param);

        })
      }

    </script>

  </head>
  <body>

    <button id="button1">异步访问AjaxServlet</button>
    <div id="div1" style="border: antiquewhite solid 1px;width: 100px;height: 100px;"></div>

  </body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值