如何从同一个函数中调用ajax函数?

时间:2022-03-17 15:59:27

I want to create a polling ajax function that calls the same function all over again if a certain condition is met. How would I do this? I'm using JQuery.

我想创建一个轮询ajax函数,如果满足某个条件,它将再次调用相同的函数。我该怎么做呢?我使用JQuery。

3 个解决方案

#1


2  

Why not use jQuery's ajax callback function like this?

为什么不像这样使用jQuery的ajax回调函数呢?

function myFunc(condition) {

    $.ajax({
        type:'GET',
        url:ajaxUrl,
        data:dataObject,
        success:function(response) {
            if (!condition) {
                myFunc(newCondition);
            }
        }
    }); 
}
myFunc();

This will call the same function over and over until the condition is true.

这将反复调用相同的函数,直到条件为真。

jQuery's ajax reference page: http://api.jquery.com/jQuery.ajax/

jQuery的ajax参考页面:http://api.jquery.com/jQuery.ajax/

#2


1  

You could do:

你能做的:

(function poll() {   
    $.ajax({
        ...
        success:function(response) {
            if (!condition_is_met) {
                poll();
            }
        }
    });
})(); //This calls the poll function inmediatly

If you want to be executed exactly after certain time, you could do:

如果你想在一段时间后被执行,你可以这样做:

setInterval(function poll() {   
  if(condition_is_met){
    $.ajax({
        ...
        success:function(response) {
            //your code here
        }
    });
  }
}, 5000); //Execute every 5 seconds

Hope this helps. Cheers

希望这个有帮助。干杯

#3


0  

You could write a javascript function to make your ajax call and set an interval for it. Using window.setInterval.

您可以编写一个javascript函数来进行ajax调用,并为其设置时间间隔。使用setinterval。

#1


2  

Why not use jQuery's ajax callback function like this?

为什么不像这样使用jQuery的ajax回调函数呢?

function myFunc(condition) {

    $.ajax({
        type:'GET',
        url:ajaxUrl,
        data:dataObject,
        success:function(response) {
            if (!condition) {
                myFunc(newCondition);
            }
        }
    }); 
}
myFunc();

This will call the same function over and over until the condition is true.

这将反复调用相同的函数,直到条件为真。

jQuery's ajax reference page: http://api.jquery.com/jQuery.ajax/

jQuery的ajax参考页面:http://api.jquery.com/jQuery.ajax/

#2


1  

You could do:

你能做的:

(function poll() {   
    $.ajax({
        ...
        success:function(response) {
            if (!condition_is_met) {
                poll();
            }
        }
    });
})(); //This calls the poll function inmediatly

If you want to be executed exactly after certain time, you could do:

如果你想在一段时间后被执行,你可以这样做:

setInterval(function poll() {   
  if(condition_is_met){
    $.ajax({
        ...
        success:function(response) {
            //your code here
        }
    });
  }
}, 5000); //Execute every 5 seconds

Hope this helps. Cheers

希望这个有帮助。干杯

#3


0  

You could write a javascript function to make your ajax call and set an interval for it. Using window.setInterval.

您可以编写一个javascript函数来进行ajax调用,并为其设置时间间隔。使用setinterval。