简体   繁体   中英

Calling a function in JS doesn't work with arguments

In my JS file i'm calling one function from the other, at first i called it with no arguments by using only it's name handleResponse
Then i tried adding arguments (of course by changing the function signature) and didn't get anything, so i tried calling the function as handleResponse() and even that didn't work.
Why can't I call my function using brackets or using arguments ?

Here are the functions : The main :

function sendRequest()
{
    var username = "";
    var game_id = -1;
    username = document.getElementById("username").value;
    game_id = document.getElementById("game_id").value;
    req.open('GET', 'check_for_opponent.php?username='+username+'&game_id='+game_id);
    req.onreadystatechange = handleResponse(username, game_id); <--- THIS IS THE CALL
    req.send(null);
}

Calling : (I changed the body, it's irrelevant).

function handleResponse(username, game_id) {
if(req.readyState == 4) {
    // DO SOMETHING...
    }
}

}

You need to wrap that call in an anonymous function:

    req.onreadystatechange = function() {
      handleResponse(username, game_id); <--- THIS IS THE CALL
    };

The code you posted will call that handler at the point the assignment is made. Instead of that, you need to assign a function that will be called when the ready state changes.

You are supposed to set a function reference to onreadystatechange and not execute the function. You can use closures to achive what you are trying to do.

req.onreadystatechange = function(){
    handleResponse(username, game_id);
}

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