使用AJAX和XMLHttpRequest动态加载内容

下面的例子展示了你如何动态load内容。使用AJAX和XMLHttpRequest object.

<!DOCTYPE html>
<html>
<head>
    <title>Dynamically loading content using AJAX and XMLHttpRequest</title>
    <style type="text/css">
        blockquote {
            font-style: italic;
            text-align: justify;
        }
    </style>
</head>
<body>
 
    <button onclick="init('lorem.txt');">Load <em>Lorem ipsum...</em></button>
    <button onclick="init('404.txt');">Load invalid file</button>
 
    <blockquote id="output"></blockquote>
 
    <script type="text/javascript">
        var xhr;
        const debug = document.getElementById("output");
 
        function xhr_onReadyStateChangeHandler(evt) {
            var req = evt.currentTarget; // xhr
 
            switch (req.readyState) {
                case XMLHttpRequest.UNSENT:
                case 0:
                    // do nothing
                    break;
                case XMLHttpRequest.OPENED:
                case 1:
                    // do nothing
                    break;
                case XMLHttpRequest.HEADERS_RECEIVED:
                case 2:
                    // do nothing
                    break;
                case XMLHttpRequest.LOADING:
                case 3:
                    // do nothing
                    break;
                case XMLHttpRequest.DONE:
                case 4:
                    if ((req.status === 200) || (req.status === 0)) {
                        debug.innerHTML = req.responseText;
                    } else {
                        debug.innerHTML = "<h1>Unable to load text file: status=" + req.status + "</h1>";
                    }
                    break;
            }
        }
 
        function init(uri) {
            xhr = new XMLHttpRequest();
            xhr.onreadystatechange = xhr_onReadyStateChangeHandler;
            xhr.open("GET", uri);
            xhr.send();
        }
    </script>
 
</body>
</html>
 

源码下载
使用AJAX和XMLHttpRequest动态加载内容.zip



 

你可能感兴趣的:(Ajax)