1

我在通过 localhost 构建的演示页面上有这个基本的“GET”请求。json 和 html 文件都在同一个文件夹中。

http://localhost.com/test.html
http://localhost.com/myList.json

不幸的是,在提出请求时,我收到了这个错误:

Uncaught ReferenceError: results is not defined.

Uncaught TypeError: Cannot set property 'innerHTML' of null 

我的html如下。

    <html>
<head>
    <title>Test</title>
    <script type="text/javascript">
    function get_json_request() {
        var httpRequest;
        httpRequest = new XMLHttpRequest();
        httpRequest.open("GET", "myList.json", true);
        httpRequest.setRequestHeader("Content-type", "application/json", true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                var results = document.getElementById("results");
                results.innerHTML = data.user;
            } else {
                alert('There was a problem with the request.');
                }
            }
        httpRequest.send(null); 
        results.innerHTML = "Processing....";
    }
</script>
</head>
<body>
    <div id"results"></div> 
    <script type="text/javascript">get_json_request();</script>
</body>
</html>

任何帮助表示赞赏。

4

1 回答 1

1

您正在条件语句中设置对“结果”的引用。如果该变量未初始化,它自然会返回 null。

于 2013-07-01T21:20:49.503 回答