【问题标题】:innerHTML showing the function, not the return value of the functioninnerHTML 显示函数,而不是函数的返回值
【发布时间】:2013-04-09 15:40:45
【问题描述】:

试图干掉我写的一些旧的 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 中,而不是函数应该实际执行的操作。有什么想法吗?

【问题讨论】:

  • 由于 ajax 的异步特性,您的脚本无法正常工作。您还需要设置 innerHTML 异步。
  • 对...怎么样?这就是我想要弄清楚的。

标签: javascript variable-assignment anonymous-function


【解决方案1】:

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

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

【讨论】:

  • 你有一个如何使用回调来做到这一点的例子吗?
  • 只要把功能放在AJAX调用之后就出现在一个单独的函数中,调用这个函数而不是return语句。
  • 你说的是ajaxPost()里面的吗?
  • 这听起来与我正在尝试做的事情在逻辑上倒退。我想我必须将参数传递给ajaxPost(),而不是从另一个函数中获取结果。
猜你喜欢
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多