0

I am trying to display the contents of my JSON into the div class "network-info". I believe what is being written first is then overwritten by what is next in the array. What can I use to circumvent this and show everything?

    $(function() {

        var netinfo = function(data) {
            for (var i = 0; i < data.length; i++) {
                $(".network-info").html(
                    "<hr>" +
                    "<p> Adapter Name: " + data[i].name + "</p>" +
                    "<p> IP Address:  " + data[i].ip + "</p>" +
                    "<p> MAC Address:  " + data[i].mac + "</p>" +
                    "<p> Adapter ID:  " + data[i].id + "</p>" +
                    "<hr>"
                )
            }
        };

        $.ajax({
            url: "http://127.0.0.1:8080/dashboard?context=netadapters&node=5",
            dataType: 'json',
            crossDomain: true,
        }).done(function(data) {
            netinfo(data);
        });

    });
1

2 Answers 2

1

Instead of writing the output directly to HTML, build up a string and then inject the string, like this:

    var netinfo = function(data) {
        var output = "";
        for (var i = 0; i < data.length; i++) {
            output +=
                "<hr>" +
                "<p> Adapter Name: " + data[i].name + "</p>" +
                "<p> IP Address:  " + data[i].ip + "</p>" +
                "<p> MAC Address:  " + data[i].mac + "</p>" +
                "<p> Adapter ID:  " + data[i].id + "</p>" +
                "<hr>";
        }
        $(".network-info").html(output);
    };

This is actually better than appending data, because it only modifies the DOM once.

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect, thank you for showing me the correct way to append data also!
0

You are correct, the content of the .network-info element is being overwritten on each iteration of the loop.

I would suggest concatenating the string, and then setting the .html at the end. This way the browser does not have to parse the HTML and update the DOM each time...

 var netinfo = function(data) {
    var htmlResult = "";
    for (var i = 0; i < data.length; i++) {
        htmlResult +=
            "<hr>" +
            "<p> Adapter Name: " + data[i].name + "</p>" +
            "<p> IP Address:  " + data[i].ip + "</p>" +
            "<p> MAC Address:  " + data[i].mac + "</p>" +
            "<p> Adapter ID:  " + data[i].id + "</p>" +
            "<hr>"
        )
    }
    $(".network-info").html(htmlResult);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.