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

时间:2013-04-09 15:40:46

标签: javascript variable-assignment anonymous-function

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

试验()

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

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);
}

我收到的输出是:

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

我无法弄清楚为什么它会在div中使用该函数而不是该函数应该实际执行的操作。有什么想法吗?

1 个答案:

答案 0 :(得分:6)

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

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

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

 return xmlhttp.responseText;

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

<小时/> 的修改

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

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);