简体   繁体   中英

Callback in javascript ajax request

I have a function to handle an ajax request, with a callback.

What this code does is that it sends a request, and writes the response inside a div in my html page. However i encounter problems with the callback, and i am not sure if the function works properly...

So my question is about the 2 lines of code inside xmlhttp.onreadystatechange and i have highlighted them.

Code:

    function check_if_over(callback) {

        //first i collect some variables from the UI
        var val1 = $('#timer').text(),
            val2 = $('#work').val();

        var val5=val1.split(":",1);

        //I initialize the xmlhttp object
        xmlhttp=GetXmlHttpObject();

        if (xmlhttp==null)
        {
        alert ("Your browser does not support Ajax HTTP");
        return;
        }

        xmlhttp.onreadystatechange = function() {

                //*****my question is about this part inside the "if"

                if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {

                        document.getElementById('content0').innerHTML=xmlhttp.responseText;
                       callback.call(xmlhttp.responseText);

                }
        };
        xmlhttp.open('GET','Controller?action=check&timer='+val5+'&work='+val2);
        xmlhttp.send();
   }

So my question is, if the xmlhttp.onreadystatechange works properly like that, performing the task of (a) writing the appropriate code inside my div, and (b) performing the callback. Thanks!

EDIT:

So after that i do this thing, and i see that it does my prints in a non-expected way, as it skips the first print on the first iteration of this code, and makes it exactly on the time for the second iteration like that:

point 2

point 2

(small wait)

point 1

(I am basically alternating between 2 states every 1 minute, so i use this to check asynchronously something in the server-side. So this is where the checking happens.)

        check_if_over(function() {
            alert("point 1");
            over = document.getElementById("value_ok").firstChild.nodeValue;
        }
        alert("point 2");

EDIT 2:

It seems that with jquery it works perfectly,

point 2

(small wait)

point 1

point 2

(small wait)

etc..

If you're already using jQuery why not use jQuery's $.get function?

function check_if_over(callback) {
    //first i collect some variables from the UI
    var val1 = $('#timer').text(),
        val2 = $('#work').val(),
        val5 = val1.split(":",1);

    $.get('Controller?action=check&timer='+val5+'&work='+val2, function(data) {
        $('#content0').html(data);
        callback.call(data);
    });
}

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