我的代码在主函数内运行。我的代码的一部分是使用之前在函数中定义的参数发出 HTTP 请求,然后将响应写入新变量并稍后使用它。
我想在主函数之外使用 HTTP 请求排除这些步骤,而只需调用该函数并将响应写入变量中。
不幸的是我尝试了,但没有成功。
Error: variable is undefined
我的代码:
function DoWork() {
//some code
var strResponseHttpRequest;
strResponseHttpRequest = HttpRequest(strInput, function(strInput) {
console.log(strInput);
};
//continue working with the variable 'strResponseHttpRequest'
//rest of my code
}
function HttpRequest(strInput, callBackMethod) {
var objRequest = new XMLHttpRequest(); //New request object
objRequest.onreadystatechange = function() {
// Waits for correct readyState && status
if (objRequest.readyState == 4 && objRequest.status == 200) callBackMethod(objRequest.responseText)
}
objRequest.open("get", "php/get-content.php?ID=" + strInput, true);
objRequest.send();
}
希望您能帮我看看问题出在哪里。如果有更好的方法可以做到这一点,请告诉我。我将不胜感激。谢谢。
最佳答案
你的意思是异步回调吗?您需要等待,直到服务器返回正确的状态和就绪状态。
更改此:
objRequest.onload = function() {
var strResponse = this.responseText;
返回 strResponse;
};
对此:
objRequest.onreadystatechange = function() {
// Waits for correct readyState && status
if (objRequest.readyState == 4 && objRequest.status == 200) callBackMethod(objRequest.responseText);
};`
并将回调方法作为第二个参数传递给 HttpRequest(strInput, callbackMethod)
,如下所示:
strResponseHttpRequest = HttpRequest(strInput, function(responseText) {
console.log(responseText);
});
还添加 callbackMethod
作为参数,如下所示:
HttpRequest(strInput, callbackMethod)
关于javascript - 如何在HTTP请求后调用回调方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53834468/