Display HTML content from AJAX result

I am writing an application that displays a list of Job objects from an AJAX JSON response.

What is the best way to render markup from the returned data. Now I am pretty convinced that its a bad idea to create server-side HTML markup and return it from an AJAX call. From experience, it makes HTML support very difficult, and content refactoring is a nightmare, so I am returning a collection of Job objects as JSON.

The question is how to render HTML based on user input? I saw some examples of creating a markup template on a page, then use jQuery to clone and populate the corresponding insert data in the DOM.

The problem is that the template contains visible content (images, etc.), and the application needs to be degraded, so I have a relay on the page where the code is severside and is populated when the page loads if JS is not available.

Any advice would be appreciated.

+3
source share
2 answers

John Resig (jQuery dude) made a super simple template engine that you can use clients, Rick Strahl a good post about this.

Trimpath has an amazing solution for client templates called Javascript Templates - not the most imaginary of the names, but it's really nice.

google, asp.net ajax (4.0?) templating, JSON .

" HTML"?. , , HTML . , , , . , , " " HTML , " " 6 : -)

+3

HTML jQuery. - , HTML:

$.ajax({
    url: 'foo',
    dataType: 'json',
    success: function(data) {



        var container = $('<div />')
                        .attr('id', 'container');

        for(var i in data.items) {
            var child = $('<div />')
                        .addClass('container-child');

            var title = $('<p />')
                        .html(data.items[i].title)
                        .addClass('item-title');

            var description = $('<p />')
                              .html(data.items[i].description)
                              .addClass('item-description');

            child.append(title).append(description);

            container.append(child);
        }

        // Remove existing container
        $('div#container').remove();
        // And replace it with the just created one
        $('body').append(container);
    }
});

, 'dummy' HTML, . , .

+1

Source: https://habr.com/ru/post/1728162/


All Articles