晴明的博客园 GitHub      CodePen      CodeWars     

[js] Ajax、Comet

#get

            function createXHR() {
                if (typeof XMLHttpRequest != "undefined") {
                    return new XMLHttpRequest();
                } else if (typeof ActiveXObject != "undefined") {
                    if (typeof arguments.callee.activeXString != "string") {
                        var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
                                "MSXML2.XMLHttp"
                            ],
                            i, len;
                        for (i = 0, len = versions.length; i < len; i++) {
                            try {
                                var xhr = new ActiveXObject(versions[i]);
                                arguments.callee.activeXString = versions[i];
                                return xhr;
                            } catch (ex) {
                                //skip
                            }
                        }
                    }
                    return new ActiveXObject(arguments.callee.activeXString);
                } else {
                    throw new Error("No XHR object available.");
                }
            }
            var xhr = createXHR();
            xhr.onreadystatechange = function(event) {
                if (xhr.readyState == 4) {
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                        console.log(xhr.statusText);
                        console.log(xhr.responseText);
                        console.log(xhr.getAllResponseHeaders());
                        console.log(xhr.getResponseHeader("MyHeader"));
                    } else {
                        console.log("Request was unsuccessful: " + xhr.status);
                    }
                }
            };
            xhr.open("get", "example.php", true);
            xhr.setRequestHeader("MyHeader", "MyValue");
            xhr.send(null);

#get 请求传输字符串处理

            var url = 'example.php';
            url = addURLParam(url, '1hao', 'haha');
            url = addURLParam(url, '2hao', '222');
            xhr.open("get", url, true);

            function addURLParam(url, name, value) {
                url += (url.indexOf('?') == -1 ? '?' : '&');
                url += encodeURIComponent(name) + '=' + encodeURIComponent(value);
                return url;
            }

#post & FormData

<!DOCTYPE html>
<html>

    <head>
        <title>XHR</title>
    </head>

    <body>
        <script>
            document.write("<p>You browser " + (typeof FormData != "undefined" ? "does" : "doesn't") + " support the FormData type.</p>")
        </script>
        <p>Fill in the form below:</p>
        <form id="user-info">
            <label for="user-name">Name:</label><input type="text" id="user-name" name="user-name" /><br />
            <label for="user-email">Email:</label><input type="text" id="user-email" name="user-email" /><br />
            <input type="button" value="Submit" onclick="submitData()" />
        </form>
        <script>
            function createXHR() {
                if (typeof XMLHttpRequest != "undefined") {
                    return new XMLHttpRequest();
                } else if (typeof ActiveXObject != "undefined") {
                    if (typeof arguments.callee.activeXString != "string") {
                        var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
                                "MSXML2.XMLHttp"
                            ],
                            i, len;
                        for (i = 0, len = versions.length; i < len; i++) {
                            try {
                                var xhr = new ActiveXObject(versions[i]);
                                arguments.callee.activeXString = versions[i];
                                return xhr;
                            } catch (ex) {
                                //skip
                            }
                        }
                    }
                    return new ActiveXObject(arguments.callee.activeXString);
                } else {
                    throw new Error("No XHR object available.");
                }
            }

            function submitData() {
                var xhr = createXHR();
                xhr.onreadystatechange = function(event) {
                    if (xhr.readyState == 4) {
                        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                            console.log(xhr.responseText);
                        } else {
                            console.log("Request was unsuccessful: " + xhr.status);
                        }
                    }
                };
                xhr.open("post", "postexample.php", true);
//                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                var form = document.getElementById("user-info");
                xhr.send(new FormData(form));
            }
        </script>
    </body>

</html>

#timeout

  function createXHR(){
            if (typeof XMLHttpRequest != "undefined"){
                return new XMLHttpRequest();
            } else if (typeof ActiveXObject != "undefined"){
                if (typeof arguments.callee.activeXString != "string"){
                    var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
                                    "MSXML2.XMLHttp"];
            
                    for (var i=0,len=versions.length; i < len; i++){
                        try {
                            var xhr = new ActiveXObject(versions[i]);
                            arguments.callee.activeXString = versions[i];
                            return xhr;
                        } catch (ex){
                            //skip
                        }
                    }
                }
            
                return new ActiveXObject(arguments.callee.activeXString);
            } else {
                throw new Error("No XHR object available.");
            }
        }
                
        var xhr = createXHR();        
        xhr.onreadystatechange = function(event){
            try {
                if (xhr.readyState == 4){
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                        console.log(xhr.responseText);
                    } else {
                        console.log("Request was unsuccessful: " + xhr.status);
                    }
                }
            } catch (ex){
                //assume handled by ontimeout
            }
        };
        
        xhr.open("get", "timeout.php", true);
        xhr.timeout = 30000;
        xhr.ontimeout = function(){
            console.log("Request did not return in a second.");
        };        
        xhr.send(null);

#load & progress

如果没有兼容性问题。可以直接使用onload、onerror、onprogress、onloadend

#

//php
<?php
    header("Content-Type: text/plain");
    header("Content-Length: 27");
    echo "Some data";
    flush();
    echo "Some data";
    flush();
    echo "Some data";
    flush();
?>

 

#

<!DOCTYPE html>
<html>

    <head>
        <title>XHR</title>
    </head>

    <body>
        <div id="status"></div>
        <script type="text/javascript">
            function createXHR() {
                if (typeof XMLHttpRequest != "undefined") {
                    return new XMLHttpRequest();
                } else if (typeof ActiveXObject != "undefined") {
                    if (typeof arguments.callee.activeXString != "string") {
                        var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
                                "MSXML2.XMLHttp"
                            ],
                            i, len;
                        for (i = 0, len = versions.length; i < len; i++) {
                            try {
                                var xhr = new ActiveXObject(versions[i]);
                                arguments.callee.activeXString = versions[i];
                                return xhr;
                            } catch (ex) {
                                //skip
                            }
                        }
                    }
                    return new ActiveXObject(arguments.callee.activeXString);
                } else {
                    throw new Error("No XHR object available.");
                }
            }
            window.onload = function() {
                var xhr = createXHR();
                xhr.onload = function(event) {
                    if ((xhr.status >= 200 && xhr.status < 300) ||
                        xhr.status == 304) {
                        console.log(xhr.responseText);
                    } else {
                        console.log("Request was unsuccessful: " + xhr.status);
                    }
                };
                xhr.onprogress = function(event) {
                    var divStatus = document.getElementById("status");
                    if (event.lengthComputable) {
                        divStatus.innerHTML = "Received " + event.position + " of " + event.totalSize + " bytes";
                    }
                };
                xhr.open("get", "altevents.php", true);
                xhr.send(null);
            };
        </script>
    </body>

</html>

 

# IE8、9 跨域(CORS)的实现,XDR IE10开始被废弃,被 XMLHttpRequest 取代

            var xdr = new XDomainRequest();
            xdr.onload = function() {
                console.log(xdr.responseText);
            };
            xdr.onerror = function() {
                console.log("Error!");
            };
            xdr.timeout = 30000;
            xdr.ontimeout=function(){
                console.log("timeout");
            }
            xdr.open("get", "http://www.baidu.com");
            xdr.send(null);
//            xdr.open("post", "http://www.baidu.com");
//            xdr.contentType("application/x-www-form-urlencoded");
//            xdr.send('name=haha&page=2');

 #CORS  老式通用

            function createCORSRequest(method, url) {
                var xhr = new XMLHttpRequest();
                if ("withCredentials" in xhr) {
                    xhr.open(method, url, true);
                } else if (typeof XDomainRequest != "undefined") {
                    xhr = new XDomainRequest();
                    xhr.open(method, url);
                } else {
                    xhr = null;
                }
                return xhr;
            }
            var request = createCORSRequest("get", "http://www.baidu.com");
            if (request) {
                request.onload = function() {
                    //do something with request.responseText
                };
                request.send();
            }

#imgping

            var img = new Image();
            img.onload = img.onerror = function() {
                console.log("Done!");
            };
            img.src = "http://www.baidu.com";

#JSONP

            //超时,这个网站可能挂了
            function handleResponse(response) {
                console.log("You're at IP address " + response.ip + ", which is in " + response.city + ", " + response.region_name);
            }
            var script = document.createElement("script");
            script.src = "http://freegeoip.net/json/?callback=handleResponse";
            document.body.insertBefore(script, document.body.lastChild);

#comet http stream

//php
<?php
$i = 0;
while (true) {
    //input some data then refresh cache
    echo "Number is $i";
    flush();

    //wait 10 second
    sleep(10);

    $i++;
}
?>

#

            function createStreamingClient(url, progress, finished) {
                var xhr = new XMLHttpRequest(),
                    received = 0;
                xhr.open("get", url, true);
                xhr.onreadystatechange = function() {
                    var result;
                    if (xhr.readyState == 3) {
                        //get only the new data and adjust counter
                        result = xhr.responseText.substring(received);
                        received += result.length;
                        //call the progress callback
                        progress(result);
                    } else if (xhr.readyState == 4) {
                        finished(xhr.responseText);
                    }
                };
                xhr.send(null);
                return xhr;
            }
            var client = createStreamingClient("streaming.php", function(data) {
                console.log("Received: " + data);
            }, function(data) {
                console.log("Done!");
            });

#SSE、Web Sockets

 

posted @ 2016-04-02 01:36  晴明桑  阅读(156)  评论(0)    收藏  举报