Asynchronous callbacks

I wrote a function that makes an asynchronous query using jQuery.

var Site = { asyncRequest : function(url, containerId) { $.ajax({ url : url, onSuccess: function(data){ $(containerId).html(data); } }); } } 

The syntax may be a little wrong as I use notepad, but hopefully you get this idea.

I call the function:

 Site.asyncRequest('someurl', container1); Site.asyncRequest('someurl', container2); 

Both requests are sent and processed by the server. Two responses are sent back, which I expect. However, I would expect that container 1 and container 2 will contain responses from both requests.

The problem is that only the last answer is displayed, and I cannot understand why. I don't know how jQuery ajax tracks requests / responses, so maybe this is a problem.

Let's say I make 5 or 10 queries, how does jQuery ajax know which answer for which query, and where does it track it?

thanks

+5
source share
2 answers

This is apparently a problem with Javascript viewing. Try the following:

 var Site = { asyncRequest: function(url, containerId) { (function(theContainer) { $.ajax({ url: url, onSuccess: function(data) { $(theContainer).html(data); } }); })(containerId); } }; 

This creates a separate area for each function call, so the actual value pointed to by "theContainer" is different for each anonymous onSuccess function.

+5
source

What happens here is the creation of a single closure related to how the function is declared. See the “More Advanced Example” here: http://skilldrick.co.uk/2010/11/a-brief-introduction-to-closures/

Basically, containerId is shared between all instances of the anonymous onSuccess function. I have not tested this, but I believe that if you defined your asyncRequest function outside of Site , it would work.

As for a more elegant solution to this problem, maybe someone else will answer better.

+1
source

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


All Articles