Shinji
Shinji

Reputation: 1839

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

I am trying to display contents of a JSON file using the mentioned functions in the question. This is the JSON object.

It could be done directly through javascript so either as soon as the user has opened this HTML file, it displays the JSON object right away. Or maybe through a button when clicked displays the JSON object contents.

{"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..."}
    ]
}}   

Upvotes: 0

Views: 189

Answers (1)

dfsq
dfsq

Reputation: 193301

Here is a typical example of XMLHttpRequest usage to load JSON data:

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();

For demonstration purposes I'm rendering data in the div#out.

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

Upvotes: 1

Related Questions