innerHTML显示函数,而不是函数的返回值
innerHTML showing the function, not the return value of the 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中粘贴函数,而不是函数应该实际做什么。任何想法吗?
您必须通过将()
添加到其中来执行函数,否则您将收到函数体!
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);
相关文章:
- 根据是否解析了 Promise 从函数返回值
- 从Ajax函数返回值
- 如何从嵌套的API函数返回值
- 从异步函数返回值
- 我如何才能继续'如果'语句来比较作为参数的多个函数返回值
- 从节点中的回调函数返回值
- 提交时不采用函数返回值.并且没有按预期行事
- 如何从工厂传递的函数返回值
- 为什么在循环中返回时函数返回值未定义
- 从JavaScript中的嵌套函数返回值
- 存在从函数返回值的问题
- 如何从setinterval函数返回值
- javascript:从匿名函数返回值
- angularjs从html调用函数返回值
- 从命名函数返回值
- 无法从Javascript中的嵌套函数返回值
- 这是显示javascript函数返回值的最佳方式吗
- 使用ajax和回调函数向函数传递值/从函数返回值
- 构造函数中的函数返回值
- 尝试从开关语句 -JS- 中的函数返回值