JavaScript實現Ajax請求簡單示例

好久以前用過JavaScript寫Ajax請求,後來一直用JQuery,今天忽然想起來,因而參考網上的資料從新寫了一遍,在此整理並記錄下來,以備之後查看使用,也但願對初學者有所幫助!示例代碼以下: javascript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title> Ajax </title>
        <script type="text/javascript">
            var xmlHttpReq = null;//XMLHttpRequest對象
            // 去除字符串兩邊空格
            String.prototype.trim = function () {
                return this.replace(/(^\s*)|(\s*$)/g, "");
            }
            // 建立XMLHttpRequest對象
            function createXMLHttpRequest() {
                if (window.XMLHttpRequest) {// IE 7.0及以上版本和非IE的瀏覽器
                    xmlHttpReq = new XMLHttpRequest();
                } else {// IE 6.0及如下版本
                    try {
                        xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
                    }catch (e) {
                        try {
                            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
                        }catch (e) {}
                    }
                }
                if (!xmlHttpReq) {
                    alert("當前瀏覽器不支持!");
                    return null;
                }
                return xmlHttpReq;
            }
            //Ajax請求
            function tiplist(txt,requestMethod){
                var txtValue = txt.value.trim();
                if(txtValue!=""){
                    var parameter = "code="+txtValue+"&str=中文";
                    var requestURL = "http://127.0.0.1:8080/MyProj/ShowServlet";
                    xmlHttpReq = createXMLHttpRequest();
                    if("GET" == requestMethod.trim().toUpperCase()){
                        xmlHttpReq.open("GET",encodeURI(EncodeURI(requestURL+"?"+parameter)),true);
                        xmlHttpReq.setRequestHeader("If-Modified-Since","0");
                        xmlHttpReq.send("null");
                    }else if("POST" == requestMethod.trim().toUpperCase()){
                        xmlHttpReq.open("POST",requestURL,true);
                        xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
                        xmlHttpReq.send(encodeURI(encodeURI(parameter)));
                    }else{
                        alert("錯誤的請求方式!");
                        return;
                    }
                    xmlHttpReq.onreadystatechange = function(){
                        if(xmlHttpReq.readyState == 4){
                            switch(xmlHttpReq.status){
                                case 200:
                                    //var datas = xmlHttpReq.responseXML.getElementsByTagName("data");
                                    //alert(datas.length);
                                    document.getElementById("downlist").innerHTML = xmlHttpReq.responseText;
                                    break;
                                case 400:
                                    alert("錯誤的請求!\nError Code:400!");
                                    break;
                                case 403:
                                    alert("拒絕請求!\nError Code:403!");
                                    break;
                                case 404:
                                    alert("請求地址不存在!\nError Code:404!");
                                    break;
                                case 500:
                                    alert("內部錯誤!\nError Code:500!");
                                    break;
                                case 503:
                                    alert("服務不可用!\nError Code:503!");
                                    break;
                                default:
                                    alert("請求返回異常!\nError Code:"+xmlHttpReq.status);
                                    break;
                            }
                        }
                    }
                }
            }
        </script>
    </head>
    <body>
        <input type="text" id="txt" name="txt" value="" onkeyup="tiplist(this,'post');" /><br/><br/>
        <div id="downlist" style="width:200px;height:300px;background:gray;"></div>
    </body>
</html>

 

PS:在寫的過程當中遇到xmlHttpRequest對象的status返回狀態碼爲0,網上大部分說法是0表示爲請求目標地址直接返回成功狀態(即此時0也表示成功狀態,但不等同於返回200的成功狀態,200纔是真正正常的成功狀態。出現此種返回0的狀態,極可能是Ajax跨域致使,好比直接運行靜態Html頁面,請求已發佈的工程,因爲該靜態頁面未在此發佈的工程中,此時就屬於跨域,返回狀態碼0,將此靜態頁面拷貝到發佈的工程目錄並以http方式訪問,返回200的成功狀態碼)。 html

相關文章
相關標籤/搜索