damon
damon

Reputation: 269

Recursive ajax() requests

I use jQuery's ajax()to get information. I call the method when the request is successful. Here is the code:

function recursively_ajax(){
    console.warn("begin");
    $.ajax({
        type:"GET",
        url: "./JvmInfoClass",
        success: function(data){
            console.warn("get jvm info success");
            recursively_ajax();
        }
    });
}

recursively_ajax();

I make the thread sleep 3 seconds in the back-end. But the console print the message continuously not after 3 seconds. Why is this?

Upvotes: 6

Views: 22720

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38512

You can try this with ajax call async:false

var counter=0;
 function recursively_ajax()
{
var pass_data=5;
var chartMenu=['VTR','NC','RC','TOCU','TOCO','TR','COA','MP'];
$.ajax({
        type:"POST",
        async:false, // set async false to wait for previous response
        url: "url to server",
        dataType:"json",
        data:{dataMenu:pass_data},
        success: function(data)
        {
            counter++;
            if(counter < chartMenu.length){
                recursively_ajax();
            }
        }
    });
 }      
 recursively_ajax();        

Upvotes: 13

damon
damon

Reputation: 269

It's browser's cacheing problem,I append the date to the url or set the ajax cache:false,the problem is solved.Thank everyone.

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388326

in that case the bug is in the server side code because the server should sent back the response only after 3 seconds.

But I would recommend to use setTimeout() in the client side to restrict the request frequency

Try

function recursively_ajax(){
    console.warn("begin");
    $.ajax({
        type:"GET",
        url: "./JvmInfoClass",
        success: function(data){
            console.warn("get jvm info success");
            setTimeout(recursively_ajax, 3000)
        }
    });
}
recursively_ajax();

Upvotes: 12

Related Questions