Ajax的核心技术就是XMLHttpRequest,简称XHR,这是微软首先提出的,后来各大浏览器厂商觉得不错,都跟着实现了。此项技术能够以异步方式从服务器获取更多的信息,用户只要触发到某一事件,在不刷新网页的前提下,就能更新到服务器端的最新数据。比如,网页触底加载,等等。
function createXHR() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();//W3C
} else {
xhr = new ActiveXObject('MicroSoft.XMLHTTP');//IE
}
return xhr;
}
先用PHP写一段服务器脚本:test.php
<?php
echo Date('Y-m-d H:i:s');
?>
http://localhost/test.php
输出:2017-05-31 08:24:36
从服务器获取数据需要那几步?
1,创建一个ajax对象;
2,连接到服务器;
3,告诉服务器要哪个东西,(发送请求);
4,接收返回值;
下面代码可以放在某个按钮的点击事件中,或者网页滚动到底部去执行,总之就是不用刷新也可以触发执行
function createXHR() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();//W3C
} else {
xhr = new ActiveXObject('MicroSoft.XMLHTTP');//IE
}
return xhr;
}
//创建xhr
var xhr = createXHR();
//open方法只是启动一个请求以备发送,还未发送
xhr.open('get', 'test.php?rand='+Math.random(), false);
//发送请求,如果是get方式,send()不需要传递参数
xhr.send(null);
alert(xhr.responseText);//弹出时间
alert(xhr.status);//200
alert(xhr.statusText);//OK
当请求发送到服务器端,客户端(浏览器端)收到响应后,响应的数据会自动填充XHR对象的属性,这里一共讲四个属性。
- responseText : 作为响应主体被返回的文本;
- responseXML : 若果响应主体内容类型是 “text/xml” 或者 “application/xml”,则返回包含响应数据的XML DOM文档;(可忽略,XML格式的)
- status : 响应的http状态;
- statusText : HTTP 状态的说明;
事实上,只有http的状态码是200的时候,才算是真的请求成功,所以,还要添加一些判断逻辑!
function createXHR() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();//W3C
} else {
xhr = new ActiveXObject('MicroSoft.XMLHTTP');//IE
}
return xhr;
}
//创建xhr
var xhr = createXHR();
//open方法只是启动一个请求以备发送,还未发送,请求一个不存在的PHP文件
xhr.open('get', 'test_error.php?rand='+Math.random(), false);
//发送请求,如果是get方式,send()不需要传递参数
xhr.send(null);
if (xhr.status == 200) {
alert(xhr.responseText)
} else {
alert('获取数据错误,错误代码:' + xhr.status + '错误信息:' + xhr.statusText);
}