13.3 解析服务器数据

  • json 数据解析;
var jsonDate = '{"name":"说了是村长"}';
var res = JSON.parse(jsonDate);
  • 原书为 XML 解析;
var responseData = xhr.responseXML.getElementsByTagName("p");
    for (var a = 0; a < responseData.length; a++) {
    console.log(responseData[a].innerHTML);
}
  • 放个完整版的;
<!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");
                        for (var a = 0; a < responseData.length; a++) {
                            console.log(responseData[a].innerHTML);
                        }
                    } else {
                        console.log(xhr.responseText);
                        console.log("error");
                    }
                } else {
                    console.log(xhr.status);
                }
            } else  {
                console.log(xhr.readyState);
            }
        }
    </script>
</head>
<body>
<a id="makeTextRequest" onclick="return makeRequest(this.href)" href="gAddress.xml">Request a XML file</a><br>
</body>
</html>
  • gAddress.xml 文件内容
<?xml version="1.0" encoding="utf-8"?>

<content>
<name>说了是村长1</name>
<p>说了是村长2</p>
<p>说了是村长3</p>
</content>