1,Ajax 概述
异步访问: 客户端发送请求到服务器, 无论服务器是否返回响应, 客户端都可以随意进行其他操作, 不会被卡死.
Ajax 运行原理: 页面发出请求, 会将请求发送给浏览器中内置的 Ajax 引擎, Ajax 引擎会提交请求到服务器端, 等待服务器响应期间, 用户可以进行其他操作, 直到服务器端将数据返回给 Ajax 引擎后, 会出发设置的事件, 执行自定义 JS 的逻辑代码完成某种功能.
2, 使用 JS 原生 Ajax 的步骤
创建 Ajax 引擎对象
为 Ajax 引擎对象绑定监听
绑定提交地址
发送请求
接受相应数据
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="UTF-8">
- <title>
- Insert title here
- </title>
- <script type="text/javascript">
- function fn1() {
- //alert();
- // 1, 创建 Ajax 引擎对象 (所有操作都通过 Ajax 引擎对象完成)
- var xmlHttp = new XMLHttpRequest();
- // 2, 为 Ajax 引擎对象绑定监听 (监听服务器是否响应)
- xmlHttp.onreadystatechange = function() {
- //alert();
- // 5, 接收响应数据
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- var res = xmlHttp.responseText;
- document.getElementById("span1").innerHTML = res;
- }
- }
- // 3, 绑定提交地址
- xmlHttp.open("GET", "/web022/ajaxServlet?name=lisi", true);
- // 4, 发送请求
- xmlHttp.send();
- }
- function fn2() {
- // 1, 创建 Ajax 引擎对象
- var xmlHttp = new XMLHttpRequest();
- // 2, 为 Ajax 引擎对象绑定监听
- xmlHttp.onreadystatechange = function() {
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- // 5, 接受响应数据
- var res = xmlHttp.responseText;
- document.getElementById("span2").innerHTML = res;
- }
- }
- // 3, 绑定提交地址
- xmlHttp.open("POST", "/WEB022/ajaxServlet", false);
- // 4, 发送请求 (POST 提交方式需要设置一个头)
- xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- xmlHttp.send("name=zhangsan");
- }
- </script>
- </head>
- <body>
- <input type="button" value="异步访问" onclick="fn1()">
- <span id="span1">
- </span>
- <br>
- <input type="button" value="同步访问" onclick="fn2()">
- <span id="span2">
- </span>
- <br>
- <input type="button" value="测试" onclick="alert(661)">
- <br>
- </body>
- </HTML>
来源: http://www.bubuko.com/infodetail-2849815.html