Answer the question
In order to leave comments, you need to log in
What is the best way to parse the results of an ajax request?
There is a site in the listing of which data is loaded using an ajax request (initially, the page is not generated through js, but the initial view of the page is generated on the backend). Data can be of different types with different display conditions.
Actually, the question is where the data display should be formed. There are 2 options to choose from:
1) Parse the display on the backend, send it as html text, reassign events to new data.
2) Use a js template engine that will work with json data and take care of all the display logic.
- Longer data loading time (on a 50 kb / s connection, the difference between the first and second approaches is 7 and 0.8 seconds, on higher connections it is almost not felt).
In the first approach, I see the following subtleties:
+ All display generation is located in one place, which greatly simplifies site maintenance in the future.
- If the loaded html text is overgrown with javascript events, it will be more difficult to maintain it on the front.
The second approach shows the following:
+ Fast data loading.
+ It will be easier to support events on loaded objects.
- We get 2 template engines written in different languages (one is for initial loading of feeds and objects (backend), the second is written in js to generate logic for displaying received ajax data in json format.
I want to know about options for solving this issue, and how do they usually do in these cases?We have all opinions divided into 2 parties: front-enders for the second option, and back-enders for the first.Maybe there is some solution that will be satisfied with all parties?
- Complex parsing of templates in js can slow down on low-powered devices.
Answer the question
In order to leave comments, you need to log in
I do so. everything consists of blocks, where each block is some kind of html, to which its own javascript is attached, which personally hangs all sorts of handlers on this block. There are two cases: loading the entire page (that is, all blocks with all their javascripts) and reloading individual blocks in the background (so-called Ajax). in the first case, the page is actually loaded and, when ready, all the scripts that are attached to the blocks of which it consists are processed. in the second block, it is loaded onto the page (inserted in the right place, replayed, appended, or something like that) and, again, its scripts are processed (namely, not all of them). if these scripts have event bindings, then they must first be unbinded, because the block can be reloaded as many times as you like, and each time the events will be hung again and pressing the button will send not one request, but as many times as the block was reloaded. there was never any trust in any .on() .live() and so on. it is easier and more reliable to replace a piece of code on the page and rebind everything that concerns it.
an additional advantage is that all the logic happens on the php side, and on the browser side only work with the house, no calculations, well, or only those that will not be lost after the block is reloaded or forced to write the same thing 2 times. only simple manipulations and processing of events that will inform the server about changes. for example, some form of sending an order, how much horror I have seen when the delivery conditions are calculated on the page with a javascript and then it is sent to the server (that is, I can change the cost in the request) or on the server, a similar algorithm considers all this again to type check , as a result, there is a mirror of the algorithm in another language, and something needs to be changed in 2 places, puzzling. or we accidentally press f5 and everything flies because no one knew about the data in the fields except for the page. as it is correct in this case (IMHO of course), let's say the form is as follows, 2 fields name and phone number and one switch delivery / pickup. we make for it in the session an array of which is able to store the state of these fields and the switch, we set the default values \u200b\u200bin the same place. when loading a page with this form, it is simply displayed with the values that are in the session. a javascript is attached to it that rebinds the keyup event on the fields and the click event on the switch. on the keyup event, the value of the field is sent to save it in the session (nothing happens in response, it is not needed here). by clicking on the switch, a request is also sent that changes its state in the session and in response the entire form is reloaded (based on the current data in the session) and everything on it is rebinded again. I don't know if I could explain
all these kilobytes and milliseconds are complete nonsense, all disputes on this topic are defending their knowledge of certain technologies. as for me, if the program is in php, then all the logic in php should take place, and js should only serve the interface and nothing more
If you use https://github.com/bem/bh and https://github.com/bem/bh-php (templates are almost 1-in-1 there, up to $ in variables), then you can unload templates and to the front, and on the back end to collect what you need.
It is even better to use a layer on nodejs purely for building html for the first run, search engines, people without JS, and not think about it in general, but leave all the logic in PHP and use it as an API.
Also, to reduce the size of the transmitted data:
a) gzip;
b) raw json
c) protobuf.
If you transfer only what you need and not get lost, you need to do two-pass templating, i.e. in 2 steps - 1) convert from raw data to some intermediate view-oriented json, and then collect html from the latter using templates on matchers.
If you like to experiment, you can also try this:
// Допустим, у нас есть выгруженные шаблоны на фронт
bh.match('users-list', function ... );
bh.match('user', function ... );
// etc.
// дальше мы должны получить данные с бекенда, для простоты укажем их явно
var usersFromBackend = [{name: 'Vasya', id: 5}, {id: 42, name: 'Petya'}, ...];
// как получили — собираем каким-то образом некую view-ориентированную структуру типа:
var viewOriented = {
// здесь можно использовать и что-то более умное
block : 'users-list',
content : fromBackend.map(function (el) {
return {
block : 'user',
// привязываем к users-list по БЭМ
// (мало ли понадобится что-то в стилях-скриптах подтюнить)
mix : { block : 'users-list', elem : 'item' },
// выводим контент в каждый div
content : {
block : 'link',
mix : { block : 'user', elem : 'link' },
url : el.url || '/users/' + el.id,
text : el.name
}
};
})
};
// И после получаем готовый HTML еще одной операцией, который останется куда-то вставить
console.log(bh.apply(viewOriented));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question