简体   繁体   中英

assigning a callback function to a variable

I am passing a callback function as below but I am not able to call this function when onreadystatechange changes it value ie request.onreadystatechange = func. I am getting a proper response from the server when I am calling the ajax request,but this method func is not getting called. Please note that func is passed as string when I call getFromServer("http://localhost/ch02/checkName.php?username=sas","func")

function createRequest() {
    try {
        request = new XMLHttpRequest();
    }
    catch (failed) {
        request = null; }
    finally  {
        return request;
    }
}

function func(){
    alert("ok");
}

function getFromServer(url,readystateCallback) {
    request=createRequest();
    if (request == null) {
        alert("unable to create request");
    } else {
        request.open("GET", url, true);
        var func= new Function (readystateCallback);
        request.onreadystatechange = func;
        request.send(null);
    }
    return request;
}

If the function is defined in the global scope, it will be added to the window object, so you can do:

var func = window[readystateCallback];

But rather than depending on this, you should make your own object that maps function names to functions. This way, you can access functions in a local scope, and you also can't inadvertently call some unexpected function as a callback.

function func() {
    alert("ok");
}
function otherfunc() {
    alert("really great");
}
...

var callbacks = {
    "func": func,
    "otherfunc": otherfunc,
    ...
}

Then you can do:

function getFromServer(url,readystateCallback) {
    request=createRequest();
    if (request == null) {
        alert("unable to create request");
    } else {
        request.open("GET", url, true);
        var func= callbacks[readystateCallback];
        request.onreadystatechange = func;
        request.send(null);
    }
    return request;
}

But the real, best solution is not to pass a function name in the first place. Just pass the function itself, this is how practically all Javascript interfaces that use callbacks work. So you should call it this way:

getFromServer("http://localhost/ch02/checkName.php?username=sas", func);

Then you simply do:

request.onreadystatechange = readystateCallback;

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