HTML as a result for calling AJAX (PROs an CON)

What is your opinion (PRO an CONS) about returning HTML code as a result for calling AJAX. This is if the application creates a new item in the list and needs some additional parameters or some template customization, instead of changing it via JS, we can send it templatized via an AJAX call.

The fact is that HTML fragments are sent from the server to the client computer and integrated into the DOM document. Any problem with this approach?

+6
source share
3 answers

There is no problem with this at all, a perfectly normal and reasonable thing.

Sometimes it’s possible to use data to send data, rather than markup and expand it using templates on the client side, but mainly for situations when you send a lot of data and therefore want to save the size on the wire, (For example, a large table in which the view HTML is 100 thousand, but raw data, for example, in JSON format, is only 10 thousand). Or when patterns vary depending on client-side conditions. But overall, great for sending HTML, you then include in the DOM via innerHTML (or any wrappers from several libraries for it that help you with odd jitter).

+6
source

This is a general approach.

If you add items to the list or replace the contents of the container with something completely different, that’s fine.

It also makes it easy to apply AJAX to existing sites (like overlays or something else) because you can query existing pages and then select unnecessary bits.

However, it would be better for updates where only the value changes, then you might need to use Json there.

+4
source

Personally, I almost always prefer to get a JSON response without using markup or formatting, but this is only because I like to have a very flexible granular response so that I can do whatever I want with the returned data, without being able to remove it from the HTML. This is not necessarily the easiest or most elegant solution in many cases! :)

+2
source

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


All Articles