V
V
vincent_gun2018-11-21 15:30:49
HTML
vincent_gun, 2018-11-21 15:30:49

SpringMVC + JSON + Ajax how to process JSON array and add code to HTML?

Good time!

I am developing an application using Spring MVC. Using JSON, I return an array to the client, intercept it in Ajax:

<...>
}).done(function (result) {

        alert(JSON.stringify(result));

    })
<...>


Under result, the required array is returned. For example:
[
{"id":97,"routeName":"Msk - SPb","stationName":"Moscow","dateArrival":"","dateDeparture":"2018-11-21 10:00:00.0"},
{"id":98,"routeName":"Msk - SPb","stationName":"Pskov","dateArrival":"2018-11-21 15:40:00.0","dateDeparture":"2018-11-21 15:50:00.0"},
{"id":99,"routeName":"Msk - SPb","stationName":"Saint Petersburg","dateArrival":"2018-11-21 19:10:00.0","dateDeparture":""}
]


Tell me or direct me in the right direction how to parse this array and add it to the html page code in the form of a table (I'm not strong in JS). The array is always returned complete with a new value, the action occurs when the "add" button is pressed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ihor Bratukh, 2018-11-21
@BRAGA96

Well, in short, something like this:

ajax('https://example.com/stations', { //> https://example.com/stations?country=russia&limit=10
    country: 'russia',
    limit: 10
}).done(function (data) {
    var table = '';
    for (var key in data) {
        table += templateDOM(data[key]) || '';
    }
    $('body').append('<table>' + table + '</table>');
});

function ajax(link, params, setup) {
    return $.ajax($.extend(true, {}, {
        method: 'GET',
        dataType: 'json'
    }, setup || {}, {
        url: link + (params ? '?' + $.param(params) : '')
    }));
}

function templateDOM(data) {
    return `
        <tr>
            <td>${data.id}</td>
            <td>${data.routeName}</td>
            <td>${data.stationName}</td>
            <td>${data.dateArrival || '-----'}</td>
            <td>${data.dateDeparture}</td>
        </tr>
    `;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question