记录学习Ajax,主要来源于传智播客于洋的学习视频资料
AJAX : 异步 javascript和 XML
AJAX :带来用户体验改变,是web优化一种主要手段AJAX = DHTML (HTML、CSS、JavaScript ) + XMLHttpRequest 对象
传统web交互模型,浏览器直接将请求发送给服务器,服务器回送响应,直接发给浏览器, Ajax交互模型,浏览器首先将请求 发送 Ajax引擎(以XMLHttpRequest为核心),AJax引擎再将请求发送给 服务器,服务器回送响应先发给Ajax引擎,再由引擎传给浏览器显示
1、同步交互模式,客户端提交请求,等待,在响应回到客户端前,客户端无法进行其他操作
2、异步交互模型,客户端将请求提交给Ajax引擎,客户端可以继续操作,由Ajax引擎来完成与服务武器端通信,当响应回来后,Ajax引擎会更新客户页面,在客户端提交请求后,用户可以继续操作,而无需等待 。
下面一个简单的Ajax的入门案例,同时也是苦逼的HelloWorld的。
1.创建XMLHttpRequest对象
2.将状态触发器绑定到一个函数
3.使用open方法建立与服务器的连接
4.向服务器端发送数据
5.在回调函数中对返回数据进行处理
<script type="text/javascript">
//创建XMLHttpRequest
function createXMLHttpRequest() {
try {
xmlHttp = new XMLHttpRequest();
} catch (tryMS) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlHttp = null;
// 这里可以报一个错误,无法获得 XMLHttpRequest对象
}
}
}
return xmlHttp;
}
//第一步创建XMLHttpRequest
var xmlHttp = createXMLHttpRequest();
//第二部 将状态触发器绑定到一个函数
xmlHttp.onreadystatechange = function() {
// 第五步,响应返回后执行
// 状态依次 是 0 - 4
// 0 未初始化
// 1 正在加载
// 2 已经加载
// 3 交互中
// 4 响应完成
if (xmlHttp.readyState == 4) {
// 判断数据是否正确
if (xmlHttp.status == 200) {
// 响应有效
alert("响应返回了..." + xmlHttp.responseText);
}
}
};
//第三步,建立连接
//get
//xmlHttp.open("GET","helloword?name=账上"); helloworld 代表 Servlet URL
//post
xmlHttp.open("POST","helloword");
//第四步 发送数据
//xmlHttp.send(null); get
//post
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
xmlHttp.send("name=李四");
</script>
下面来写一个servlet来和页面交互
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
System.out.println("ajax相应收到了。。。。。。。。");
//获得参数
String name = request.getParameter("name");
name = new String(name.getBytes("ISO-8859-1"),"utf-8");
System.out.println(name);
response.setContentType("text/plain;charset=utf-8");
response.getWriter().print("ajax响应数据");
}
这样一个简单的helloworld就好了
总结一下,
XMLHttpRequest
方法: open send
属性:
onreadystatechange :状态回调函数
responseText/responseXML :服务器的响应字符串
status:服务器返回的HTTP状态码
statusText: 服务器返回的HTTP状态信息
readyState :对象状态
客户端向服务器提交数据
1、get方式发送数据
xmlHttp.open("GET","url?key=value"); // 参数已经在url上
xmlHttp.send(null);
2、post方式发送数据
xmlHttp.open("POST","url"); // 不需要写参数
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded"); // post发送参数前,需要设置编码格式
xmlHttp.send("name=xxx&pwd=xxx"); // 发送post数据
回调函数编写
if(xmlHttp.readyState == 4){
// 判断数据是否正确
if(xmlHttp.status == 200){
// 响应有效
...
}
}