简体   繁体   中英

Using AJAX to grab JSON data then output data by ElementID on HTML

I am currently new to using AJAX and JSON and I am stuck on something that may be simple to you.

I am to use AJAX to grab data from JSON then from there, I will need to be inputting the data into specified ElementIDs on my HTML Page.

The data is Paragraphs and I am stuck on the Javascript part where I am to grab my data from JSON then to a ElementID on my HTML Document.

JSON

{

    "Paragraphs": [

        {
            "Paragraph1": "Hi! I am Person."
        },

        {
            "Paragraph2": "My name is Person and I am a web designer from a Place."
        }

    ]
}

JS

(function () {


    "use strict";
    // Instantiate new xhr object
    var dataFile = "scripts/app.json";
    var request = new XMLHttpRequest();
    request.open('GET', dataFile, true);
    request.addEventListener('readystatechange', function () {
        // wait for file to finish loading
        if (request.readyState === 4) {
            var paragraph = {};

            // read in the json object
            paragraph = JSON.parse(request.responseText);


            // declare local paragraph array container
            var paragraphArray = [];

            // read in the paragraphs array from the json object
            paragraphArray = paragraph.Paragraphs;

            //store
            var paragraphArrayLength = paragraphArray.length;
            //loop
            for (var number = 0; number < paragraphArrayLength; number++) {
                var paragraph = document.getElementById('Paragraph1' + 'Paragraph2' + (number + 1));
                Paragraphs.Paragraph1.innerHTML = paragraphArray[number];
                paragraphs.Paragraph2.innerHTML = paragraphArray[number];
            }
        }
    });
    request.send();

})();

HTML

<div class="container">
    <div class="jumbotron">
        <div class="text-center">
            <h1 id="Paragraph1"></h1>
            <img src="images/portfolio.jpg" class="img-circle" alt="Cinque Terre" width="150" height="150">
            <p class="lead" id="Paragraph2"></p>
            </ul>
        </div>
    </div>
</div>

Please help! Thank you 8)

This will use the keys in the objects in the Paragraphs array as the IDs of the elements to fill in with the values.

for (var i = 0; i < paragraphArrayLength; i++) {
    for (var id in paragraphArray[i]) {
        document.getElementById(id).innerHTML = paragraphArray[i][id];
    }
}

The nested loops are necessary because your array elements are objects, and the property names are different in each object. I recommend changing the JSON structure so it's more uniform, eg

{

    "Paragraphs": [

        {
            "id": "Paragraph1",
            "value": "Hi! I am Person."
        },

        {
            "id": "Paragraph2",
            "value": "My name is Person and I am a web designer from a Place."
        }

    ]
}

Or make Paragraphs an object instead of an array, where the IDs are the keys of that object.

            for (var number = 0; number < paragraphArrayLength; number++) {
            var paragraph = document.getElementById('Paragraph' + (number + 1);

            paragraph.innerHTML = paragraphArray[number -1].keys['Paragraph' + number];
        }

When you iterate the paragraphs, you should set each one to a local var. That way you have 1 paragraph that you are working on, per iteration.

Your html and javascript both contain errors that need fixing. For example, the html has an extra ul tag and "Paragraphs" should be "paragraphs" in your loop.

Yet, the data format might be the reason you are having a difficult time. You have an array of objects and each object has a key with a different name. And while you can do it that way, it makes it more difficult to work with. In contrast, an array of strings would be far easier. Also see Barmar's solution which another commonly used alternative.

To make it easier to understand, I've removed all the extraneous code, including the loop. The snippet simply writes each paragraph 1 and 2. Yet, some of the other solutions here show you how to loop through the data too.

Run the snippet to try it.

 // simulated ajax data var request = { responseText: '{"Paragraphs":[{"Paragraph1":"Lions and tigers"},{"Paragraph2":"and bears"}]}' }; // if (request.readyState === 4) { ... var paragraph = JSON.parse(request.responseText); var paragraphArray = paragraph.Paragraphs; document.getElementById('Paragraph1').innerHTML = paragraphArray[0].Paragraph1; document.getElementById('Paragraph2').innerHTML = paragraphArray[1].Paragraph2;
 <h1 id="Paragraph1"></h1> <p class="lead" id="Paragraph2"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM