簡體   English   中英

如何使用xmlhttprequest和僅與HTML / Jscript異步顯示JSON對象?

[英]How to display JSON objects using xmlhttprequest and asynchronous with only HTML/Jscript only?

我正在嘗試使用問題中提到的功能來顯示JSON文件的內容。 這是JSON對象。

可以直接通過javascript完成,因此只要用戶打開此HTML文件,它就會立即顯示JSON對象。 也可以通過單擊按鈕顯示JSON對象內容。

{"menu": {
"header": "SVG Viewer",
"items": [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    null,
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "OriginalView", "label": "Original View"},
    null,
    {"id": "Quality"},
    {"id": "Pause"},
    {"id": "Mute"},
    null,
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"},
    {"id": "ViewSource", "label": "View Source"},
    {"id": "SaveAs", "label": "Save As"},
    null,
    {"id": "Help"},
    {"id": "About", "label": "About Adobe CVG Viewer..."}
    ]
}}   

這是使用XMLHttpRequest加載JSON數據的典型示例:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);

xhr.onreadystatechange = function() {
    if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
            var data = JSON.parse(this.responseText);
            document.getElementById('out').innerHTML = JSON.stringify(data, null, '  ');
        }
    }
};

xhr.send();

出於演示目的,我在div#out渲染數據。

演示: http : //plnkr.co/edit/0wZ79wbmSYSalyIP96x7?p=preview

暫無
暫無

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

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