Answer the question
In order to leave comments, you need to log in
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>
[{id: "1", user_id: "id", username: "name"},{...}]
Answer the question
In order to leave comments, you need to log in
$.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 questionAsk a Question
731 491 924 answers to any question