您的位置:首页 > 其它

【ajax基础篇】——同步与异步

2016-07-14 09:08 302 查看
AJAX是异步的javascript xml,特征就是允许浏览器与服务器通信而无须刷新当前页面。

一:同步事件

//跨浏览器添加事件
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn);
} else {
obj.attchEvent("on" + type, fn);
}
};

//同步方式
addEvent(document, "click", function () {
var xhr = new XMLHttpRequest();//创建xhr
xhr.open('get', 'test.xml? rand=' + Math.random, false);  //准备发送请求,以get方式请求,url是test.xml,同步
xhr.send(null); //发送请求,get不需要数据提交,则填写为null
//alert(xhr.responseText);  //打印出服务器端打印回来的数据
// alert(xhr.status);  //获取当前数据的是否成功,成功返回的是200
//alert(xhr.statusText);//获取成功或失败后返回的文本,成功返回OK
if (xhr.status == 200) {
alert(xhr.responseText);
} else {
alert('获取数据错误!错误代码:' + xhr.status + '错误信息:' + xhr.statusText);
}
});


二 :异步事件

//使用异步方式
addEvent(document, "click", function () {
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {  //只有当页面完成及接受全部的相应后,才真正的使用。分为了xhr.readystate==1,启动;2,发送,3,接受,4,完成。
if (xhr.status == 200) {
alert(xhr.responseText);
} else {
alert('获取数据错误!错误信息:' + xhr.status + '错误信息:' + xhr.statusText);
}
};
}

xhr.open('get', 'test.xml? rand=' + Math.random, true);
xhr.abort();  //取消异步的函数。
xhr.send(null);
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: