函数返回Javascript中未定义的
无法确定如何从此函数返回值(字符串):函数返回Javascript中未定义的,javascript,function,function-declaration,function-expression,Javascript,Function,Function Declaration,Function Expression,无法确定如何从此函数返回值(字符串): function loadPage(url) { var xhttp = new XMLHttpRequest(); xhttp.open("GET", url, true); xhttp.send(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) {
function loadPage(url) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//var html = xhttp.responseText
var html = document.documentElement.outerHTML;
return html
}
}
}
console.log(loadPage("http://stops.lt/vilnius/#trol/2/a-b"))
当我在
xhtp.onreadystatechange
中使用console.log(html)
时,它会打印正确的结果,但我不知道如何返回loadPage(url)
。尝试了返回xhtp.onreadystatechange
和返回xhtp.onreadystatechange()
函数loadPage是异步的,您需要使用回调函数(或承诺):
异步编程101:请至少阅读ajax部分谢谢链接。我对Javascript非常陌生。这是我用js.async编程101编写的第一个脚本的一部分:请至少阅读ajax部分谢谢链接。我对Javascript非常陌生。这是我用js编写的第一个脚本的一部分。承诺不太受支持(例如IE11),只需使用回调即可。承诺不太受支持(例如IE11),只需使用回调即可。
function loadPage(url, cb) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//var html = xhttp.responseText
var html = document.documentElement.outerHTML;
cb(html);
}
}
}
loadPage("http://stops.lt/vilnius/#trol/2/a-b", function(html){
console.log(html);
});