V
V
Vladislav Kolotsei2016-03-25 00:12:09
JavaScript
Vladislav Kolotsei, 2016-03-25 00:12:09

Why are a large number of requests sent from AJAX?

Faced the following problem. There is a page with a menu and an area with dynamic content. When you click on a menu item in the area, another page is loaded via ajax.

After the first click on the link in the menu, one request is sent to the server via ajax, after the second click on the menu item, two requests are sent to the server, etc. That is, after each click on the menu item, the number of requests doubles. And after 10 clicks on the menu item, the server starts to get very stupid.

I do not understand why this is happening, tell me, what could be the problem? Below is a photo of the

link code that sends a request to the server:

<p><a class="links view">Просмотр справочника</a></p>

ajax code to send request to server:
$(".view").click(function() {
    console.log("ajax view");
    $.ajax({  
      type: "POST",
          url: "actionController",
          data: {command: 'view', start: '0'},
          success: function(html){ 
          	$("#workplace").html(html);
          }
      });
  });

Console log:
fb5680f91c6e42f2956b360c0b3205b0.JPG

Updated:
Ajax code: https://jsfiddle.net/Vlady_32/uo7o375s/

Java code (servlet, command handler): https://jsfiddle.net/Vlady_32/jhm9gzf1/
I had to insert java code into html, js, css. I'm sorry.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey, 2016-03-25
@vlady_32

Perhaps you are executing the above code several times, thereby adding the same handlers.
You need to look at a more complete code, as well as what you are loading via ajax - maybe there is also javascript there.
Well, or you have another div class="view" loaded into an existing div class="view" and click fires on each one.

A
Andrew, 2016-03-25
@iCoderXXI

Try preventDefault() and stopPropagation()
I wouldn't use links by reassigning event handlers to them. Despite the fact that this is a very common practice, it personally causes dissonance for me. It's like buying a caterpillar tractor, cutting off its tracks, attaching wheels and cutting it like that, rejoicing at your ingenuity...
:) vision of rationality and common sense - HTML generated on the server roads. Today it is fashionable to receive JSON from the server, and to drive out the client-side templating. This is an order of magnitude more economical, so the same shelesya in the data center will withstand an order of magnitude more load ...
And if you also cache typical repetitive things ...

S
SecurityCodeNAS, 2016-03-25
@SecurityCodeNAS

Try checking like this
$(".view").off().click(function() {
console.log("ajax view");
$.ajax({
type: "POST",
url: "actionController",
data: {command: 'view', start: '0'},
success: function(html){
$("#workplace").html(html);
}
});
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question