13.6 用 Ajax 预览链接

  • 结合之前的动态展示 div 将请求到的数据 display
  • 简单举例,随便写的;
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script>

        var xhr = false;
        function makeRequest(url) {
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                if (window.ActiveXObject) {
                    try {
                        xhr = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) {
                        console.log(e);
                    }
                }
            }

            if (xhr) {
                xhr.onreadystatechange = showContents;
                xhr.open("GET", url, true);
                xhr.send(null);
            } else {
                console.log("xhr 不存在");
            }
            return false;
        }

        function showContents() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
                        var responseData = xhr.responseXML.getElementsByTagName("p");

                        var newDiv = document.createElement("div");
                        newDiv.setAttribute("id","dd");

                        for (var a = 0; a < responseData.length; a++) {
                            var t = document.createTextNode(responseData[a].innerHTML);
                            newDiv.appendChild(t);
                        }
                        var oldDiv = document.getElementById("dd");
                        oldDiv.style.display = "block";
                        document.body.replaceChild(newDiv,oldDiv);

                    } else {
                        console.log(xhr.responseText);
                        console.log("error");
                    }
                } else {
                    console.log(xhr.status);
                }
            } else  {
                console.log(xhr.readyState);
            }
        }

        function leave() {
            var dd = document.getElementById("dd");
            dd.style.display = "none";
        }
    </script>
</head>
<body>
<a id="makeTextRequest" onmouseover="return makeRequest(this.href)"  onmouseleave="leave()" href="gAddress.xml">Request a XML file</a><br>
<div id="dd" style="display: none;">
</div>
</body>
</html>