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

innerHTML showing the function, not the return value of the function

本文关键字:函数 返回值 显示 innerHTML      更新时间:2023-09-26

尝试删除我写的一些旧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中粘贴函数,而不是函数应该实际做什么。任何想法吗?

您必须通过将()添加到其中来执行函数,否则您将收到函数体!

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