AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”
特点:1、与服务器异步交互; 2、 浏览器页面局部刷新;
优点:
缺点:
AJAX就是在Javascript中多添加了一个对象:XMLHttpRequest对象。所有的异步交互都是使用XMLHttpRequest对象完成的
各个浏览器对XMLHttpRequest的支持也是不同的!
大多数浏览器都支持DOM2规范,都可以使用:var xmlHttp = new XMLHttpRequest()来创建对象;
但IE有所不同,IE5.5以及更早版本需要:var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”)来创建对象;
而IE6中需要:var xmlHttp = new ActiveXObject(“Msmxl2.XMLHTTP”)来创建对象;
而IE7以及更新版本也支持DOM2规范。
步骤
1) 创建XMLHttpRequest对象、XMLHttpRequest()
2) 打开XMLHttpRequest与服务器的连接 ,调用XMLHttpRequest的open()
open(method, url, async):
3) 发送请求, ,调用XMLHttpRequest的send() 、 xmlHttp.send(null);
注意:若没有参数,需要给出null为参数!若不给出null为参数,可能会导致FireFox浏览器不能正常发送请求!
4) 接收服务器的响应
XMLHttpRequest绑定了一个事件, 状态改变的事件
XMLHttpRequest对象有一个onreadystatechange事件,它会在XMLHttpRequest对象的状态发生变化时被调用
0:初始化未完成状态,只是创建了XMLHttpRequest对象,还未调用open()方法;
1:请求已开始,open()方法已调用,但还没发送请求
2:请求发送完成状态,send()方法已调用;
3:开始读取服务器响应;
4:读取服务器响应结束。
通过XMLHttpRequest对象的readyState属性来得到XMLHttpRequest对象的状态
可以通过XMLHttpRequest对象的status属性得到服务器的状态码, HTTP状态码, 关注200,表示成功
5) 获取服务器的响应的数据
通过XmlHttpRequest对象responseText属性获取
发送的GET请求: 可以通过url传递参数、也可以通过send方法
发送的POST请求: 请求参数必须通过send方法发送
一定设置请求体的编码:xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
但在使用AJAX发送请求时,就没有默认值了,这需要我们自己来设置请求头:)
设置请求头, 一定要在open()之后
html代码:
<h1 style="height:200px; width:400px; background-color: red;">第一个AJAX页面</h1> <div id="box" style="height: 200px; width: 300px; background-color: green;" >我是div, 我准备学习AJAX</div> <button type="button" onclick="changeBox()">按钮</button>
javascript代码
<!--浏览器兼容问题--> <script type="text/javascript"> //创建XMLHttpRequest对象的函数 function createXmlHttpRequest(){ var xmlHttp; // 适用于大多数浏览器,以及IE7和IE更高版本 try{ xmlHttp = new XMLHttpRequest(); } catch (e) { // 适用于IE6 try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { // 适用于IE5.5,以及IE更早版本 try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ alert("兄弟,你这是什么浏览器"); } } } return xmlHttp; }
具体实现代码
function changeBox(){ // 发送的同步请求 //location.href="/ajax01/AServlet"; //发送异步请求 //1.创建XMLHttpRequest对象 var xmlHttp = createXmlHttpRequest(); //0 //2.打开与服务器的连接、GET请求: 传递参数: 通过url传递参数 xmlHttp.open("GET","/day_12Ajax/AServlet?name=lisi"); //1 //2.1 post提交需要设置请求头 //xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 通过send函数传递参数 key=value&key2=value2.... //xmlHttp.send("name=wangwu"); //3.发送请求 // GET请求: 传递参数1) 通过send函数传递参数 xmlHttp.send(null); //2 //4.绑定一个监听xmlHttpRequest对象状态改变的事件 xmlHttp.onreadystatechange = function(){3 if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ //服务器响应完成, 双层保证4 //5.获取服务器响应的数据5 var obj = eval("("+xmlHttp.responseText+")"); alert(obj.age ); //将数据放入标签中 document.getElementById("box").innerHTML=xmlHttp.responseText; } } } </script>
servlet代码:json格式传输
response.getWriter().print("{\"name\":\"zhangsan\",\"age\":\"21\"}");
原文:https://www.cnblogs.com/64Byte/p/12939414.html