Ajax是Asynchronous Javascript And XML的缩写,它是一种技术。php
这一技术可以向服务器请求额外的数据而不用卸载页面。html
会带来更好的用户体验。前端
早在Ajax出世以前,Ajax式的通讯要经过一些Hack才能完成,大多数是使用隐藏的框架或内嵌框架。(很遗憾我不是在那个时期成长起来的,因此就不太熟悉了,大概是利用iframe来实现的,只不过是不跨域而已)ajax
在Ajax出世以前,有一种叫远程脚本的技术,它的工做和Ajax相似。Javascript要借助Java applet或者Flash等中间件才能实现。(具体是怎么来作的,我也不是很清楚,大概的原理是Javascript与中间件通讯,中间件再与服务器通讯)跨域
Ajax技术的核心是XMLHttpRequest对象(简称XHR)。浏览器
下面只对xhr的大概过程做了简单的介绍,若是想深刻了解ajax,你们能够深刻了解了一下xhr的各个属性、方法和过程。服务器
function createXHR(){ if(typeof XMLHttpRequest != 'undefined'){ return new XMLHttpRequest(); }else if(typeof ActiveXObject != 'undefined'){// for IE6- if(typeof arguments.callee.activXString != 'string'){ var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp',], i, len; for(i=0, len=versions.length; i<len; i++){ try{ new ActiveXObject(versions[i]); arguments.callee.activXString = versions[i]; break; }catch(e){} } } return new ActiveXObject(arguments.callee.activXString); }else{ throw new Error('No XHR object available.'); } }
var xhr = createXHR(); xhr.open('get', 'example.php', false); xhr.send(null);
var xhr = createXHR(); xhr.onreadystatechange = function(){ if(xhr.readyState ==4){ if(xhr.status>=200 && xhr.status < 300 || xhr.status == 304){ console.log(xhr.responseText); }else{ console.log('Request was unsuccessful'+xhr.status); } } }; xhr.open('get', 'example.txt', true); xhr.send(null);
W3C开始着手xhr的规范化,xhr2进一步发展了xhr。app
FormData用于对表单的序列化,好处是没必要明确在xhr对象上设置请求的头部。xhr可以识别出FormData数据,并设置相应的头部。框架
xhr.open('get', 'example.txt', true); var form = document.getElementById('form1'); xhr.send(FormData(form));
timeout属性表示在请求多少毫秒以后就中止请求。异步
xhr.open('get', 'example.txt', true); xhr.timeout = 1000; xhr.timeout = function(){ console.log('Request not return in a second'); } xhr.send(null);
load用以代替readystatechange+readyState
xhr.onload = function(){ if(xhr.status>=200 && xhr.status < 300 || xhr.status == 304){ console.log(xhr.responseText); }else{ console.log('Request was unsuccessful'+xhr.status); } } xhr.open('get', 'example.php', false); xhr.send(null);
onprogress事件会接收一个event对象,它的target就是xhr,此外还包含了三个额外的属性:lengthComputable表示进度信息是否可用, position表示已经接收的数据的字节数, totalSize表示根据Content-Length响应头部肯定的预期字节数。有了这些信息,咱们就能够向用户展现一个进度条了。
xhr.onload = function(){ if(xhr.status>=200 && xhr.status < 300 || xhr.status == 304){ console.log(xhr.responseText); }else{ console.log('Request was unsuccessful'+xhr.status); } }; xhr.onprogress = function(event){ var divStatus = document.getElementById('status'); if(event.lengthComputalbe){ divStatus.innerHTML = 'Received ' + event.position + 'of' + event.totalSize + 'bytes'; } }; xhr.open('get', 'example.php', false); xhr.send(null);
这个我在前端解决跨域问题的8种方案(最新最全)中提到过,就不在这里介绍了。
Comet指的是一种服务器推送技术,它是一种更加高级的Ajax技术。Comet分为轮询和HTTP流两种形式。
var source = new EventSource('myevents.php'); source.onmessage = function(event){ var data = event.data; ...... }
这个我也在前端解决跨域问题的8种方案(最新最全)中提到过,就不在这里介绍了。
从Ajax的发展来看,它是愈来愈成熟,愈来愈强大,它不只在无刷新方面提高了用户体验,也在跨域访问中有着出色的能力。