簡體   English   中英

AJAX XMLHttpRequest錯誤

[英]AJAX XMLHttpRequest error

我在通過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>

任何幫助表示贊賞。

您在條件語句中設置對“結果”的引用。 如果未初始化該變量,則它自然會返回null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM