JavaScript实现Ajax请求简单示例

原文链接:https://my.oschina.net/u/658145/blog/167651

很久之前用过JavaScript写Ajax请求,后来一直用JQuery,今天突然想起来,于是参考网上的资料重新写了一遍,在此整理并记录下来,以备以后查看使用,也希望对初学者有所帮助!示例代码如下:

<!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的成功状态码)。

猜你喜欢

转载自blog.csdn.net/u013252072/article/details/52995087