Ajax - XMLHTTPRequest

addLoadEvent.js

function addLoadEvent(func){  
    var oldonLoad = window.onload;  
    if(typeof window.onload!='function'){  
            window.onload = func;  
    }  
    else{  
        window.onload = function(){  
            oldonload();  
            func();  
        }  
    }  
}  

getHTTPObject.js

function getHTTPObject(){
    if (typeof XMLHttpRequest == "undefined") {
        XMLHttpRequest = function(){
            try {
                console.log("Xsml2.XMLHTTP.6.0")
                return new ActiveXObject("Xsml2.XMLHTTP.6.0");
            } catch (error) {
                
            }
            try {
                console.log("Xsml2.XMLHTTP.3.0")
                return new ActiveXObject("Xsml2.XMLHTTP.3.0");
            } catch (error) {
                
            }
            try {
                console.log("Xsml2.XMLHTTP")
                return new ActiveXObject("Xsml2.XMLHTTP");
            } catch (error) {
                
            }
            return false;
        }
    }
    console.log("XMLHttpRequest")
    return new XMLHttpRequest();
}

getNewContent.js

function getNewContent() {
    var request = getHTTPObject();

    if (request) {
        /*    
            open(method,url,async)
            method:请求的类型;GET 或 POST
            url:文件在服务器上的位置
            async:true(异步)或 false(同步)
        */
        request.open("GET", "example.txt", true);
        /*onreadystatechange:服务器在 XMLHTTPRequest 对象发回响应时候被触发*/
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                //readyState:0 未初始化,1正在加载 ,2加载完毕,3正在交互,4完成
                var para = document.createElement("p");
                /*
                    返回的数据有2个属性:
                    responseText:获得字符串形式的响应数据
                    responseXML:获得 XML 形式的响应数据(用于保存Content-Type头部中指定“text/xml”的数据,
                    其实是一个DocumentFragment对象) 
                 */
                var txt = document.createTextNode(request.responseText);
                para.appendChild(txt);
                document.getElementById('new').appendChild(para);
            }
        };
        request.send(null); //send(string)  string:仅用于 POST 请求
    } else {
        alert("Sorry, your browser doesn\'t support XMLHttpRequest.");
    }
}
addLoadEvent(getNewContent);

Ajax

AJAX使用XMLHTTPRequest对象发送的请求只能访问与其所在的HTML处于同一域中的数据,不能发送请求。此外,有些浏览器还会限制 AJAX 请求使用的协议。比如,Chrome,如果使用 file://协议从自己硬盘加载example.txt,会看到Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

posted @ 2017-11-12 15:36  【唐】三三  阅读(212)  评论(0编辑  收藏  举报