Javascript xmlhttp.onreadystatechange在异步调用中仅触发一次
这是我的js代码Javascript xmlhttp.onreadystatechange在异步调用中仅触发一次,javascript,asynchronous,xmlhttprequest,Javascript,Asynchronous,Xmlhttprequest,这是我的js代码 function makeAsynchronousPostHttpCall(url, params, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("POST", url, true); // false for synchronous request xmlHttp.setRequestHeader('Content-type', 'application/
function makeAsynchronousPostHttpCall(url, params, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", url, true); // false for synchronous request
xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlHttp.send(params);
xmlHttp.onreadystatechange = callback(xmlHttp);
return xmlHttp.responseText;
}
function fooBar() {
var url = foo;
var config = bar;
var params = "config=" + config;
var callback = (xmlHttp) => {
console.log(xmlHttp.readyState);
if(xmlHttp.readyState == 1){
document.getElementById('progress').innerHTML = 'Request in Progress For '+ config;
document.getElementById('completedMessage').innerHTML = "";
}
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById('progress').innerHTML = 'Request Completed For '+ config;
document.getElementById('completedMessage').innerHTML = xmlHttp.responseText;
}
}
makeAsynchronousPostHttpCall(url, params, callback);
}
所有w.r.t的请求和响应都正常工作。请求成功,我得到了预期的响应。但问题是我的“xmlHttp.onreadystatechange”回调只触发了一次。i、 e在控制台日志中,我只能找到“1”。但当我使用同步调用时,同样的情况也很好。我的页面正在使用我已完成的邮件进行更新。但是使用异步调用时,页面会被更新为“Request in Progress For bar”,但一旦请求完成,我就看不到页面中有任何进一步的更改
使用异步调用时是否有捕获
谢谢
.onreadystatechange
需要是一个函数-您没有将其设置为函数xmlHttp.onreadystatechange=()=>callback(xmlHttp)代码>@JaromandaX,很抱歉我没能理解你。我已经为var'callback'分配了一个函数,并将其分配给xhr.onreadystatechange。我做错了什么?xmlHttp.onreadystatechange=callback(xmlHttp)
立即调用callback(xmlHttp)
,并将该函数返回的值赋给xmlHttp.onreadystatechange
。。。调用函数和(这是您正在做的)和引用函数以分配给任何(这是您需要做的)示例var a=Math.random()
立即执行Math.random()
,与您所做的没有区别doing@JaromandaX是的,那是个错误。。。谢谢