简体   繁体   中英

jQuery - how to call ajax when certain condition is met

I know you can use the function setInterval to call your ajax function at fixed time interval. What I'd like to achieve though is something like this:

while (true) //but obviously this while loop will block other code. I'd like it non-blocking
{   //if certain condition is met, call my ajax function.
}

so basically the code should sit silently in the background, listening. if certain condition is meet, fire ajax call.

Is is possible in jquery/javascript?

Edit: For conditions: basically, I will be automatically scrolling the rows of a large table (that is another question, another post...), once it reaches the last row, the condition is met, ajax is called to fetch data from the server, re-populate the table, and start automatically scrolling again.

In Javascript, conditions do not "become met" all by themselves.

It's (mostly) a single threaded language, where the UI thread just sits around waiting for events to happen, and in response the programmer supplied event handlers go do stuff. So long as they're doing stuff, the UI thread is unable to handle any more events.

This is why you shouldn't ever use a busy loop, or otherwise tie up the CPU doing long-winded calculations in a tight loop.

In summary, you shouldn't ever need to poll a condition - it should be evident when that condition becomes true because some event will have fired, allowing it to become true .

You should then be able to fire off your AJAX request in that event's handler .


EDIT you've now clarified that you want to do this when the scroll reaches the end of a table.

Per above, there is (of course) an event that tells you that something scrolled, and it'll tell you how far.

Look at http://api.jquery.com/scroll/

You need to register a handler for that event, and then trigger your AJAX call in that handler .

Certainly possible if you have an event. Then you can attach a handler to it. So the question is: what condition ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM