AJAX
Asynchronous JavaScript And Xml 异步的
JavaScript:更新局部的网页
XML:一般用于请求数据和响应数据的封装
XMLHttpRequest对象:发送请求到服务器并获得返回结果
CSS:美化页面样式
异步:发送请求后不等返回结果,由回调函数处理结果
一、JavaScript版本
<script>
var xmlRequest = null;
function ajaxLogin(){
var username = document.getElementById("nameID").value;
var userpass = document.getElementById("passID").value;
//1.创建XMLHttpRequest对象
xmlRequest = new XMLHttpRequest();
//2.绑定用于接受响应消息的回调函数
xmlRequest.onreadystatechange = onRequest;
//3.打开一个URL(请求地址),指定请求方法(还未发出请求)
xmlRequest.open("post","AjaxLoginServlet",true);//true表示异步,false表示不异步
//4.在真正发送之前,我们可以设置请求头
//本例设置为模拟form表单提交,让服务器认为本次请求时form表单提交的
xmlRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//5.使用send真发出请求,并发送附加数据(若有的话)
xmlRequest.send("username="+username+"&userpass="+userpass);
/*
xmlRequest.open("get","AjaxLoginServlet?username="
+username+"&userpass="+userpass,true);
xmlRequest.send();
*/
}
//当准备状态码变化时,就会调用此方法
function onRequest(){
//只有准备状态码为4,且响应状态码为200时,认为响应完成并成功!
if(xmlRequest.readyState ==4 && xmlRequest.status == 200){
//从XMLHttpRequest对象中,获取响应的正文(responseText或responseXML)
var message = xmlRequest.responseText;
//var message = xmlRequest.responseXML;
//接下来是对响应信息进行处理
//如果message是json字符串,那么可以转换成js中的Json对象
var jsonObj = JSON.parse(message);
alert(jsonObj.maxPage);
}
}
</script>
readystate:XMLHttpRequest的状态信息
就绪状态码 | 说明 |
---|---|
0 | XMLHttpRequest对象没有完成初始化 |
1 | XMLHttpRequest对象开始发送请求 |
2 | XMLHttpRequest对象的请求发送完成 |
3 | XMLHttpRequest对象开始读取响应,还没有结束 |
4 | XMLHttpRequest对象读取响应结束 |
<script>
var xmlHttpReq = null;
function sendAjaxRequest(urlAndParam,onResponse,async){
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.onreadystatechange = onResponse;
xmlHttpReq.open("post",urlAndParam,async);
xmlHttpReq.send(null);
}
</script>
二、JQuery版本
<script>
$(function(){
$("#sendText").click(function(){
var strToSend = $("#strID").val();
//接收普通文本消息
$.post("JQueryAjaxServlet",{sendMsg:strToSend},function(msg){
$("receiveText").text(msg);
});
//接收Json数据,必须在后台设置响应头"application/json"或"text/json"
$.post("JQueryAjaxServlet",{sendMsg:strToSend},function(jsonObj){
$("receiveText").text(jsonObj.received);
});
});
});
</script>
<script>
//ajax请求另一个页面load
<script type="text/javascript">
$(function(){
//前端静态ajax
$("#fh").hide();
$("#zc").click(function(){
$("#bd").load("staticRegist.form");
$("#fh").show();
});
$("#fh").click(function(){
$("#bd").load("staticLogin.form");
});
$("#bd").load("staticLogin.form");
});
</script>