简体   繁体   中英

Why is my AJAX function calling the callback multiple times?

I've made an ajax post function, and when I call it once, the callback function that is passed to it ends up getting called 3 times. Why is the callback being called multiple times?

I'm attempting to use a "module" javascript pattern that uses closures to wrap like functionality under one global variable. My ajax module is its own file, and looks like this:

var ajax = (function (XMLHttpRequest) {
    "use strict";

    var done = 4, ok = 200;

    function post(url, parameters, callback) {

        var XHR = new XMLHttpRequest();

        if (parameters === false || parameters === null || parameters === undefined) {
            parameters = "";
        }

        XHR.open("post", url, true);
        XHR.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        XHR.onreadystatechange = function () {
            if (XHR.readyState === done && XHR.status === ok) {
                callback(XHR.responseText);
            }
        };
        XHR.send(parameters);
    }

    // Return the function/variable names available outside of the module.
    // Right now, all I have is the ajax post function.
    return {
        post: post
    };

}(parent.XMLHttpRequest));

The main application is also it's own file. It, as an example, looks like this:

// Start point for program execution.

(function (window, document, ajax) {
    "use strict";

    ajax.post("php/paths.php", null, function () { window.alert("1"); });

}(this, this.document, parent.ajax));

As you can see, I'm trying to bring in dependencies as local variables/namespaces. When this runs, it pops up the alert box 3 times.

I'm not sure if this problem is due to the ajax function itself or the overall architecture (or both), so I'd appreciate comments or thoughts on either.

I've tried un-wrapping the main part of the program from the anonymous function, but that didn't help. Thanks in advance!

EDIT: Here's the entire HTML file, so you can see the order I include the <script> 's in.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="expires" conent="0" />
    <title>Mapalicious</title>
    <link href="css/main.css" type="text/css" rel="stylesheet" />
    <script src="js/raphael.js"></script>
</head>
<body>
    <div id="map"></div>
    <script src="js/promise.js"></script>
    <script src="js/bigmap.js"></script>
    <script src="js/ajax.js"></script>
    <script src="js/init.js"></script>
</body>
</html>

EDIT 2:

I had a typo in my example, and changed

(function (window, document, bigmap, ajax) {

to

(function (window, document, ajax) {

EDIT 3:

I've changed the onreadystatechange function to log the ready state to the console:

XHR.onreadystatechange = function () {
    console.log("readyState: " + XHR.readyState);
    if (XHR.readyState === done && XHR.status === ok) {
        callback(XHR.responseText);
    }
};

When I step through the code in Google Chrome, the callback is called three times, and the console logs:

readyState: 4
readyState: 4
readyState: 4

However, when I run the page as normal and don't step through it, the function works as expected and only runs the callback once. In this case, the console logs:

readyState: 2
readyState: 3
readyState: 3
readyState: 4

So now my question is, why is the callback called multiple times when stepping through code?

SOLVED:

When I asked this question, I didn't realize that it was only happening when I was stepping through the code while debugging .

So , the state changed 3 times, but execution has been delayed by the break-point, so all 3 onreadystatechange functions see the current state of 4, instead of what the state was when the change actually occurred.

The takeaway is that onreadystatechange change does not store what that state is. Instead, it reads the readyState at the time its executed, even if the program gets interrupted, and the state changes again in the mean time.

Therefore, AJAX requires different debugging techniques than you use with completely synchronous code... but you probably already knew that.

Thanks to everyone who helped out here.

The readyState has 4 distinct states:

0 - no request initialized
1 - connected to server
2 - request was received
3 - processing
4 - Done, response received

Each of these changes will call the onreadystatechange handler. That's why most of these functions will look like this:

xhr.onreadystatechange = function()
{
    if (this.readyState === 4 && this.status === 200)
    {
        //do stuff with this.responseText
    }
}

Just hard-code them, instead of using dodgy variables (the names done and ok seem dangerous to me).

Other than that, try declaring the post function either directly in the returned object:

return {post : function()
{
};

Or as an anon. function, assigned to the variable post :

var post = function(){};

Various engines do various things with functions, the way you declare them, hoisting them, for one. Also post doesn't feel right as a function name if you ask me... I'd try to use names that don't look like they might be reserved...

Also, you're not explicitly setting the XHR's X-Requested-With header:

XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Which might just be what's causing the problem (HTTP1.1 and transfer-encoding chunked?)

To make debugging easier, try logging the XHR object each time the alert shows up by changing callback(XHR.responseText); to callback.apply(this,[this.responseText]); , although the argument is redundant. Then, change ajax.post("php/paths.php", null, function () { window.alert("1"); }); to:

ajax.post("php/paths.php", null,
function (response)
{
     console.log(this.readyState);//or alert the readyState
     window.alert(response);//check the response itself, for undefined/valid responses
});

It looks to me like your ajax object is returning a call to the post function. If this is so, and you are invoking the post function on the ajax variable, wouldn't it call post at least twice: once on instantiation of the object and next on the method call?

I am quite new in using ajax, but I have the same problem that I am trying to solve. I have been reading about ajax in w3chools. I have noticed that when the state is checked, they use this.readystate and this.status not the object.readystate . I think for some reason it fires three times on object.readystat e and works fine with this.readystate . I will check it tomorrow, but I think that might be the problem.

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