关于AJAX的一些总结

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格式的响应数据

转载于:https://www.cnblogs.com/riverdeng/archive/2011/08/09/2132732.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值