AJAX,即Asynchronous Javascript And XML(异步Javascript和XML),它可以通过js对服务器进行发起请求,局部刷新页面.
AJAX的核心对象为XMLHttpRequest,值得注意的是IE6及其以下的版本不支持此对象,与之对应的是ActiveXObject对象.
故而,为了兼容个浏览器版本,应该采取以下的方式得到XMLHttpRequest对象:
1 function AjaxRequest( ){
2 var xmlHttp = null;
3 if (window.XMLHttpRequest) {
4 xmlHttp = new XMLHttpRequest();
5 } else {
6 xmlHttp = ActiveXObject("Microsoft.XMLHttp");
7 }
8 }
AJAX的核心方法有open,send
open(method,url,asyn):
method的值为POST|GET.POST方式没有长度限制,GET方式反应更快
url为请求的URI
asyn:
true表示异步请求,false表示同步请求.不建议将asyn设为false,因为同步请求会阻塞线程,仅当请求的内容很短小是可以设为false
当设置为false的时候,不需要编写onreadystatechange函数,只需要将要需要执行的代码放在send()的后面即可
send(string)
string参数仅用于POST方式
function AjaxRequest() {
var xmlHttp = null;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = ActiveXObject("Microsoft.XMLHttp");
}
xmlHttp.open("GET", "../AjaxRequest.aspx", false);
xmlHttp.send();
var response = xmlHttp.responseText;
}
AJAX的核心属性有onreadystatechange,readystate,status.
onreadystatechange,实际上是一个回调函数,当readystate改变的时候则会触发onreadystatechange事件.
readystate属性分别有以下值:
0:请求未初始化
1:与服务器建立连接
2:已与服务器建立连接成功,请求已接收
3:请求正在处理中
4:请求已完成,相应已就绪
status属性分别有以下值:
200:"ok",即正常状态
404:未找到页面
function AjaxRequest() {
var xmlHttp = null;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = ActiveXObject("Microsoft.XMLHttp");
}
xmlHttp.onreadstatechange = function() {
if (readystate == 4 && status == 200) {
var response = xmlHttp.responseText; //xmlHttp.responseXML;
//TODO 对响应数据进行处理
}
}
xmlHttp.open("GET", "../AjaxRequest.aspx", false);
xmlHttp.send();
}
取得服务器相应有两个属性:responseText,responseXML
responseText,字符串格式的响应数据
responseXML,XML格式的响应数据