Ajax常用写法

Just make a note!

var xmlHttpReq;

function createXmlHttpRequest() {

    //创建XMLHttpRequest对象

    if(window.XMLHttpRequest) {

        xmlHttpReq = new XMLHttpRequest();

        if(xmlHttpReq.overrideMimeType) {

            xmlHttpReq.overrideMimeType('text/xml');

        }

    } else if(window.ActiveXObject) {

        try {

            xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");

        } catch (e) {

            try {

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

            } catch (e) {

            }

        }

    }

    if(!xmlHttpReq) {

        alert('Can not create XMLHTTP instance!');

        return false;

    }

}



//入口,调用Ajax请求

function callAjax() {

    createXmlHttpRequest();

    var url = "xxxxx";



    var query = "methodName=run?a=2";//传递请求的参数

    xmlHttpReq.open("POST", url, true);

    xmlHttpReq.onreadystatechange = callBack;//指定回调函数

    xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xmlHttpReq.send(query);//发送请求的参数

}



//回调函数

function callBack() {

    if(xmlHttpReq.readyState == 4) {

        if(xmlHttpReq.status == 200) {

            var returnStr = xmlHttp.responseXML; // xmlHttp.responseXML 即为执行后台操作后,返回的值

                // do what you want with responseXML

        }

    }

}

 

 

你可能感兴趣的:(Ajax)