M
M
MrJobs2021-01-10 17:47:18
JSON
MrJobs, 2021-01-10 17:47:18

How to get json correctly?

Hello, I'm trying to populate a table from a json file.

$(document).ready(function() {

$.ajax({
    url: 'json_input_url',
    data: {},
    dataType: "json",
        cache: false,
        success: function (data) {
        $.each(data, function (i, val) {
            var tr = "<tr>" +
                "<td>"+ (i + 1) + "</td>" +
                "<td>"+ val.id + "</td>" +
                "</tr>";
            $(tr).appendTo("tbody");
        });
    }
});

});

<tbody id="items">

    </tbody>

JSON structure
[{id: "1", user_id: "id", username: "name"},{...}]

And everything seems to be fine, but my table is still not there
. I see it in the console, it's not on the page, tell me, please, where is the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Ezhgurov, 2021-01-10
@eandr_67

$.each is for jQuery sets. And for JavaScript arrays there is forEach: https://learn.javascript.ru/array-iteration

$(document).ready(function () {
    $.ajax({
        url: 'json_input_url',
        data: {},
        dataType: "json",
        cache: false,
        success: function (data) {
            console.log(data); // увидеть в консоли, что реально пришло
            data.forEach(function (val, i) {
                var tr = "<tr>" +
                    "<td>" + (i + 1) + "</td>" +
                    "<td>" + val.id + "</td>" +
                    "</tr>";
                $('#items').append(tr);
            });
        }
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question