ajax的使用步骤详解

1、引言

就是异步刷新,AJAX要和XMLHttpRequest对象、JavaScript/DOM、CSS、XML一起使用

2、XMLHttpRequest对象

XMLHttpRequest对象,异步的与服务器交换数据,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新
XMLHttpRequest对象是ajax的基础
语法

var xhr = new XMLHttpRequest();

2.1 语法格式

如需将请求发送到服务器,使用XMLHttpRequest()对象的open()、send()方法
send发送的数据,给到open方法的url定义的页面里面

方法 描述
open(method,url,async 规定请求的类型、URL以及是否异步处理请求。method:请求的类型(GET或者POST);url:文件在服务器上的位置;async:true(异步)或false(同步),这个是默认true的不用设置
send(string) 将请求发送到服务器。string:仅用于POST请求

2.2 get请求代码

2.2.1 一个简单的GET请求
<script type="text/javascript">
var xhr = new XMLHttpRequest();
    xhr.open("get", "data",true);
    xhr.send();
</script>

其中的data是一个Servlet页面

2.2.2 url加唯一的ID

在上面的例子中,您可能得到的是缓存的结果,为了避免这种情况,向URL添加一个唯一的ID(t=Math.random())

<script type="text/javascript">
	 var xhr = new XMLHttpRequest();
     xhr.open("get","data?t="+Math.random(),true)
   	 xhr.send(); 
</script>
2.2.3 通过GET方法发送数据

向URL添加信息(username = zhangsan、password = 123)

<script type="text/javascript">
 	var xhr = new XMLHttpRequest();
    xhr.open("get","data?username=zhangsan&password=123",true)
    xhr.send();
</script>
2.3 post请求代码

一个简单的POST请求

<script>
    var xhr = new XMLHttpRequest();
    //一个简单的POST请求
    xhr.open("POST","data",true);
    xhr.send(); 
</script>

如果需要像html的form表单那样post数据,请使用setRequestHeader()添加HTTP头,在send()方法中规定发送的数据

<script>
    var xhr = new XMLHttpRequest();
    xhr.open("POST","data",true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send("username=zhangsan&password=123");
</script>
2.4 readyState

语法

<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.open("get", "data",true);
    xhr.send();
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
</script>

每当readyState改变时,就会触发。onreadystatechange事件
在onreadystatechange事件中,添加任务
readyState属性存有XMLHttpRequest的状态信息
当readyState等于4且状态为200时,表示响应以就绪

属性 描述
onreadystatechange 存储函数(或函数名),每当readyState属性改变时,就会调用该函数。
readyState 存有XMLHttpRequest的状态。从0到4发生变化。0:请求未初始 1:服务器连接已建立 2:请求已接收 3:请求处理中 4:请求已完成,且响应已就绪
status 例:200:“OK”;404:未找到页面

3、例题1–用alert在浏览器输出servlet页面定义的字符串

servlet页面代码

@WebServlet(name = "DataServlet", value = "/data")
public class DataServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String mess = "刘雨昕新歌未知计划上线啦!!!!";
        PrintWriter printWriter = response.getWriter();
        printWriter.write(mess);
        printWriter.flush();
        printWriter.close();
    }

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

html页面代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.open("post", "data",true);
    xhr.send();
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
</script>
</body>
</html>

四、post例题

点击显示div内容

@WebServlet(name = "DataServlet", value = "/data")
public class DataServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        PrintWriter printWriter = response.getWriter();
        printWriter.write("name:"+name+",password:"+pwd);
        printWriter.flush();
        printWriter.close();
    }

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #div1 {
            width: 200px;
            height: 100px;
            border: solid 2px rgba(255, 43, 10, 0.96);
        }
    </style>
</head>
<body>
<button id="btn">点击显示div</button>
<div id="div1"></div>
<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.open("post", "data", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("name=zhangsan&pwd=123");
    var div = document.getElementById("div1");
    var btn = document.getElementById("btn");
    btn.addEventListener('click', () => {
            div.innerText = xhr.responseText;
    })

</script>
</body>
</html>

你可能感兴趣的:(javaweb,servlet,ajax,javaweb)