Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - setInterval and Ajax

I have this problem when I use setInterval and ajax for retrieving data from the database and if the data that I retrieve from the database is equal to saveHere then it will loop again until it does not match the variable saveHere, it freeze the browser until the data that I retrieve is not equal to saveHere.

Here is an example:

var saveHere = 'RED';
var interval = setInterval(function() {

    var sample = $.ajax({
        type: 'GET',
        url: 'database.php',
        data : data
    }).responseText;

    if (sample != 'RED') {
        clearInterval(interval);
        saveHere = sample;
    }
    else {
        console.log('load again');
    }

},1000);

I really need advice. Thank you in advance. Sorry for the grammar.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$.ajax is asynchronous and requires you to use a callback to get the response text.

Take a look at the documentation at http://api.jquery.com/jQuery.ajax/

What you want to do is to add a success parameter. Something like this:

var saveHere = 'RED';

doAjax();

function doAjax() {

    $.ajax({
        type: 'GET',
        url: 'database.php',
        data: data,
        success: function (sample) {
            if (sample != 'RED') {
                saveHere = sample;
            } else {
                console.log('load again');
                doAjax();
            }
        }
    });

}

Notice how I've removed setInterval and instead wrapped the Ajax code in a function. The success callback will be called when the Ajax query has successfully finished, and give you the response. Once we have evaluated the response, we can run the doAjax function again to run the query again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...