JS 原生的 Ajax 其实就是围绕浏览器内内置的 Ajax 引擎对象进行学习的, 要使用 JS 原生的 Ajax 完成异步操作, 有如下几个步骤:
1) 创建 Ajax 引擎对象
2) 为 Ajax 引擎对象绑定监听 (监听服务器已将数据响应给引擎)
3) 绑定提交地址
4) 发送请求
5) 接受响应数据
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="UTF-8">
- <title>
- Insert title here
- </title>
- <script type="text/javascript">
- function fn1() {
- //1, 创建 Ajax 引擎对象 ---- 所有的操作都是通过引擎对象
- var xmlHttp = new XMLHttpRequest();
- //2, 绑定监听 ---- 监听服务器是否已经返回相应数据
- xmlHttp.onreadystatechange = function() {
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- //5, 接受相应数据
- var res = xmlHttp.responseText;
- document.getElementById("span1").innerHTML = res;
- }
- }
- //3, 绑定地址
- xmlHttp.open("GET", "/web22/ajaxServlet?name=lisi", true);
- //4, 发送请求
- xmlHttp.send();
- }
- function fn2() {
- //1, 创建 Ajax 引擎对象 ---- 所有的操作都是通过引擎对象
- var xmlHttp = new XMLHttpRequest();
- //2, 绑定监听 ---- 监听服务器是否已经返回相应数据
- xmlHttp.onreadystatechange = function() {
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- //5, 接受相应数据
- var res = xmlHttp.responseText;
- document.getElementById("span2").innerHTML = res;
- }
- }
- //3, 绑定地址
- xmlHttp.open("POST", "/WEB22/ajaxServlet", false);
- //4, 发送请求
- xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- xmlHttp.send("name=wangwu");
- }
- </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()">
- </body>
- </HTML>
注意:
注意: 如果是 post 提交
在发送请求之前设置一个头
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
get 请求的请求参数在 open(如 fn1 中的参数传递方法) 中或 send 中都可以 (如 fn2 中的参数传递方法)
来源: http://www.bubuko.com/infodetail-3066703.html