ajax
介绍
什么是 AJAX ?
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。
基本原理
ajax原理
1、创建xhr对象
XMLHttpRequest(简称xhr)是AJAX的基础,前后端的交互,消息的传递都是用xhr来进行。
xhr在不同内核的创建方式是不同,通过window.XMLHttpRequest来却分不同内核。
- ie内核通过ActiveX对象
variable=new ActiveXObject("Microsoft.XMLHTTP");
- 基本其他的内核均采用`variable=new XMLHttpRequest();
2、向服务器发送请求
如需将请求发送到服务器,需要用xhr的open()以及send()方法
xml=new XMLHttpRequest();
xml.open("GET",url);
xml.senf();
/*GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
无法使用缓存文件(更新服务器上的文件或数据库)
向服务器发送大量数据(POST 没有数据量限制)
发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠*/
get用法
这个例子有一个表单,如果输入框失焦则进行ajax请求。
$(function(){
//1.获取用户输入值
//2。发送xhr请求
//3。创建xhr对象
$("#username").blur(function(){
var username=$(this).val();
console.log(username);
var xhr;
if(window.XMLHttpRequest){
xmhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
//向服务器发送请求
xhr.open("GET","${pageContext.request.contextPath}/user/chackName?username="+username);
xhr.send();
/*如果onreadystatefunction是4则表示请求完整,status==200表示正常*/
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){}
console.log(xhr.responseText);
//从response拿到消息,显示结果
$("msg").text(xhr.responseText);
}
});
});
<form action="" >
username:<input type="text" id="username"><span id="msg"></span>
后端接受服务器请求,将要传回的消息放入response中,然后在前端由xhr拿到。
action代码
public String checkName() throws IOException {
//收集数据
//调用业务
HttpServletResponse response= ServletActionContext.getResponse();
if("zhangsan".equals(username)){
response.getWriter().print("正确");
}else {response.getWriter().print("错误");
}
return null;
}
post用法
xhr进行post请求服务的操作与使用get的基本一样。
不同点在于post请求他的参数不是在url中传送,而是在send()方法中。
xhr.open("Post","${pageContext.request.contextPath}/user/checkName");
//设置xhr消息的编码方式,不然不能传出值
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("username="+username);
其他的地方和get方法一致。