Ajax通信步骤

来源:互联网 发布:苹果手机网络设置 编辑:程序博客网 时间:2024/06/16 01:04

(一)创建XMLHttpRequest对象:

重要属性有:status、statusText、

    function CreateRequestObject() {

        var ajaxObject ;

        try{

            ajaxObject = new XMLHttpRequest() ;        //Opera 8.0+ , Firefox , Safari

        }catch(e){

            //Internet Explorer

            try{

                ajaxObject = new ActiveXObject("Msxm12.XMLHTTP") ;       

            }catch(e){

                try{

                    ajaxObject = new ActiveXObject("Microsoft.XMLHTTP") ;

                }catch(e){

                    return false ;

                }

            }

        }

        return ajavObject ;

    }

(二)初始化对象

1、调用open()方法为同服务器间通信的对象做准备并初始化,通过send()方法发出实际请求。open()方法包括三个参数:请求类型(POST\GET\...)、URL以及键值对参数、可选参数(true异步/fasle同步,默认true)。

2、GET和POST,post需要发送额外的数据:setRequestHander("Content-type", "application/x-www-form-urlencodes");

3、最后通过send()方法把请求发到服务器。

    eg:  (1)  ajaxObject.open("GET","URL",true) ;            

                  ajaxObject.send(null) ;

           (2)  ajaxObject.open("POST","URL",true);

                  ajaxObject.setRequestHander("Content-type", "application/x-www-form-urlencodes");

                  ajaxObject.send();

(三)监控服务器响应状态

监听XMLHttpRequest对象的onreadystatechange()事件,在触发时调用函数

eg:ajaxObject.onreadystatechange = function() {

            if( ajaxObject.readyState == 4) {

                if(ajaxObject.status == 才200) {

                    //执行成功,处理结果

                }else if (ajaxObject.status == 404){

                    //404错误

                }

            }

        }