如何正确返回功能?

时间:2017-04-02 08:14:14

标签: javascript

function checkAnswer(id, answer) {
    answer = answer.trim();
    var xhr = new XmlHttpRequest();
    xhr.open('POST', './c.php', true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log("FROM xhr: "+xhr.responseText);
             return xhr.responseText;
        }
                }
    xhr.send();

}

此功能无法正确返回。 console.log("FROM xhr: "+xhr.responseText)是有效的,但不是return语句(返回undefined)。为什么呢?

c.php我刚刚echo "OK";

我还尝试在return之后粘贴xhr.send()语句,但它也会返回undefined

1 个答案:

答案 0 :(得分:0)

您的代码执行异步(函数不等待AJAX​​响应),因此您的函数返回undefined。阅读promises