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
        }
    }
}

 

 

posted @ 2013-05-28 17:18  yejg1212  阅读(1376)  评论(0编辑  收藏  举报