回调函数无法返回

时间:2017-07-23 21:22:12

标签: javascript xmlhttprequest

我无法弄清楚为什么这个事件处理程序不会返回:

function getJSON () {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://quotes.rest/qod.json', true); 

    request.onreadystatechange = function () {
        if (request.status === 200 && request.readyState === XMLHttpRequest.DONE) {
        return 1;
        }
    }   
    request.send(null);
};

如果我用console.log()替换return语句,它会触发,所以我知道if语句的条件已经满足。

更新:

XMLHttpRequest.onreadystatechange

An EventHandler that is called whenever the readyState attribute changes. The callback is called from the user interface thread. The XMLHttpRequest.onreadystatechange property contains the event handler to be called when the readystatechange event is fired, that is every time the readyState property of the XMLHttpRequest changes.

我正在调用API并期望一旦服务器返回状态200并且readyState的状态等于4(DONE),就会触发eventhandler中的return语句 更新2:它不是重复的,因为我不会问如何返回回调响应,而只是为什么return语句无法运行

1 个答案:

答案 0 :(得分:0)

从您的问题中不清楚回调函数的位置。回调需要传递给您期望使用它的函数。因此,例如getJSON应该接受callBack作为参数(function getJSON(callBack) { }),然后return 1;应由return callBack(1);

替换