AJAX的前世今生与未来

一、通过三个问答来认识一下Ajax

什么是Ajax?

Ajax是Asynchronous Javascript And XML的缩写,它是一种技术。

Ajax有什么用?

这一技术能够向服务器请求额外的数据而不用卸载页面。

Ajax有什么好处?

会带来更好的用户体验。

二、Ajax的前世

1)前端的Ajax

早在Ajax出世之前,Ajax式的通信要通过一些Hack才能完成,大多数是使用隐藏的框架或内嵌框架。(很遗憾我不是在那个时期成长起来的,所以就不太熟悉了,大概是利用iframe来实现的,只不过是不跨域而已)

2)中间件的Ajax

在Ajax出世之前,有一种叫远程脚本的技术,它的工作和Ajax类似。Javascript要借助Java applet或者Flash等中间件才能实现。(具体是怎么来做的,我也不是很清楚,大概的原理是Javascript与中间件通信,中间件再与服务器通信)

三、Ajax的今生

Ajax技术的核心是XMLHttpRequest对象(简称XHR)。

下面只对xhr的大概过程作了简单的介绍,如果想深入了解ajax,大家可以深入了解了一下xhr的各个属性、方法和过程。

创建跨浏览器的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.');
    }
}

同步xhr

var xhr = createXHR();
xhr.open('get', 'example.php', false);
xhr.send(null);

异步xhr

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);

四、Ajax的未来

1) xhr2

W3C开始着手xhr的规范化,xhr2进一步发展了xhr。

1>FormData

FormData用于对表单的序列化,好处是不必明确在xhr对象上设置请求的头部。xhr能够识别出FormData数据,并设置相应的头部。

xhr.open('get', 'example.txt', true);
var form = document.getElementById('form1');
xhr.send(FormData(form));

2>timeout

timeout属性表示在请求多少毫秒之后就停止请求。

xhr.open('get', 'example.txt', true);
xhr.timeout = 1000;
xhr.timeout = function(){
    console.log('Request not return in a second');
}
xhr.send(null);

3>load

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);

4>progress

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);

2)CORS

这个我在前端解决跨域问题的8种方案(最新最全)中提到过,就不在这里介绍了。

3)Comet

Comet指的是一种服务器推送技术,它是一种更加高级的Ajax技术。Comet分为轮询和HTTP流两种形式。

SSE(Server Sent Event)

var source = new EventSource('myevents.php');
source.onmessage = function(event){
    var data =  event.data;
    ......
}

4)Web Sockts

这个我也在前端解决跨域问题的8种方案(最新最全)中提到过,就不在这里介绍了。

五、总结

从Ajax的发展来看,它是越来越成熟,越来越强大,它不仅在无刷新方面提升了用户体验,也在跨域访问中有着出色的能力。