innerHTML显示函数,而不是函数的返回值

jds*_*sky 1 javascript anonymous-function variable-assignment

试图干掉我写的一些旧的javascript.

测试()

function test() {
    var output = function() {
        return ajaxPost("test.php", "testvar=bananas");
    }
    document.getElementById("main").innerHTML = output;
}
Run Code Online (Sandbox Code Playgroud)

ajaxPost()

function ajaxPost(file,stuff) {
    var xmlhttp;
    var actionFile = file;
    var ajaxVars = stuff;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            return xmlhttp.responseText;
        } else {
            // Waiting...
        }
    }

    xmlhttp.open("POST", actionFile, true);

    //Send the proper header information along with the request
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.send(ajaxVars);
}
Run Code Online (Sandbox Code Playgroud)

我收到的输出是这样的:

<div id="main">
    function () { return ajaxPost("test.php", "testvar=bananas"); }
</div>
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么它将函数粘贴在div中而不是函数应该实际执行的操作.有什么想法吗?

Sir*_*rko 6

你必须通过添加()它来执行该功能,否则你会收到函数体!

function test() {
    var output = function() {
        return ajaxPost("test.php", "testvar=bananas");
    }
    document.getElementById("main").innerHTML = output();
}
Run Code Online (Sandbox Code Playgroud)

此外,您尝试从此处的AJAX调用返回一个值

 return xmlhttp.responseText;
Run Code Online (Sandbox Code Playgroud)

这不会像在异步调用中那样工作,没有任何东西可以捕获返回的值!你应该调用某种回调,它使用返回的值.


编辑

这将是一个类似于您的代码的回调方法:

function test( data ) {
    document.getElementById("main").innerHTML = data;
}

function ajaxPost(file,stuff,cb) {

    // ...

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            cb( xmlhttp.responseText );
        } else {
            // Waiting...
        }
    }
    // ...
}

// make the actual call
ajaxPost("test.php", "testvar=bananas", test);
Run Code Online (Sandbox Code Playgroud)