13.2 读取服务器数据

  • window.XMLHttpRequest 创建请求对象,一般浏览器支持本机;
  • XMLHttpRequest 对象请求数据;
  • onreadystatechange 检查请求状态;
  • 数据解析
状态值 说明
0 为初始化
1 正在加载
2 已经加载
3 交互式,未完全加载,但是可以交互
4 完全
<!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) {
                        console.log(xhr.responseXML);
                    } else {
                        console.log(xhr.responseText);
                    }
                } else {
                    console.log(xhr.status);
                }
            } else  {
                console.log(xhr.readyState);
            }
        }
    </script>
</head>
<body>
<div style="float:left;">
    <a id="makeTextRequest" onclick="return makeRequest(this.href)" href="gAddress.txt">Request a text file</a><br>
</div>
</body>
</html>