Jquery ajax calls with security scope

My gut tells me that if I am on a messy server and the user fires two events quickly enough, and the success function c will be the value of the most recent event that calls func1 to use the wrong value. & lt --- --- This is an assumption, I have not proved it. His feeling.

How can I provide the correct value when calling func1? I prefer not to send c to the server, and I don't know how and how to serialize the data and deserialize it. How to make this code safe?

$('.blah').click(function (event) { var c = $(this).closest('.comment'); ... $.ajax({ url: "/u", type: "POST", dataType: "json", data: { ... }, success: function (data) { func1(c. data.blah);//here 
+4
source share
3 answers

The this inside the onclick callback refers to the element that was clicked.

This means that the variable c will always be the closest .comment element. For example, if you click on 5 different .blah elements very quickly, it will cause 5 ajax calls and all 5 successful callbacks will have the correct area copied in which it was defined.

Thus, this is safe, since the area in which c is copied inside the success callback. Welcome to the JavaScript close feature.

+4
source

I tried something like this ...

here is the markup of the sample

 <div id="links"><a href="#">link1</a><a href="#">link2</a></div> 

then this is jquery code

 $('#links').click(function(e) { var link = $(e.target).closest('a'); if ( link.length ) { setTimeout(function() { console.log(link.text()); }, 2000); return false; } });; 

I think that you will still have the correct value in your "c" variable. In this example, I still have two console logs "link1" and "link2" even after clicking both links at a time before the 2 second timeout.

Hope this helps.

+1
source

A simple test:

 var i = 0; var f = function() { var c = ++i; setTimeout(function() { alert(c); }, i*1000); } f(); f(); f(); // alerts 1, 2 and 3 after a little delay 

shows that your gut feeling is wrong.

0
source

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


All Articles