簡體   English   中英

無法從 XMLHttpRequest 顯示 JSON

[英]Can't display JSON from XMLHttpRequest

我似乎無法弄清楚為什么此代碼不會顯示請求的 JSON。 我已將范圍縮小到最低限度,但仍然存在問題。 我沒有正確執行 XMLHttpRequest 嗎?

<html>
    <body>
            <a id="testname"></a>
            <a id="testval"></a>
    </body>
    <script>
        var request = new XMLHttpRequest();
        request.open('GET', 'test.json');
        request.responseType = 'json';
        request.send();
        request.onload = function() { 
            var test = request.response;
            document.getElementById("testname").innerHTML = test.name;
            document.getElementById("testval").innerHTML = test.val;
        };
    </script>
</html>

我相信您是在設置onload回調函數之前發送請求。 最有可能的是,在您分配回調函數之前請求已完成,因此什么也沒有發生。 查看有關send功能的文檔: https : //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

暫無
暫無

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

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