如何捕获XMLHttpRequest onreadystatechange函数结果?

时间:2014-01-19 14:34:38

标签: javascript xmlhttprequest

如果eAC_callback false true eAConreadystatechange期间调用function eAC(emailData) { if (window.XMLHttpRequest) { httpRequest = new XMLHttpRequest(); } if (!httpRequest) { return false; } var fd = new FormData(); fd.append("email", emailData); httpRequest.onreadystatechange = eAC_callback; httpRequest.open('POST', "http://example.com/p_PEC.php"); httpRequest.send(fd); } ,我想抓住true的返回值。我能这样做吗?怎么样?

false

readyState is 4status is 200

时,eAC_callback会返回function eAC_callback() { if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { var response = JSON.parse(httpRequest.responseText); if(response.error === 0){ return true; } else { if(response.error === 1){ return false; } if(response.error === 2){ return false; } } } else { return false; } } }; 或{{1}}
{{1}}

1 个答案:

答案 0 :(得分:1)

  

我想捕获eAC_callback

的返回值

然后你必须将它包装在另一个函数中:

httpRequest.onreadystatechange = function() {
    if (eAC_callback()) {
        …
    } else {
        …
    }
};

但是,您永远无法return在安装回调的eAC函数的异步回调中计算出的任何结果(很久以前)。另请参阅How do I return the response from an asynchronous call? - 提供回调或返回承诺。