Ajax响应总是在第一次调用后返回2

Ajax response always returns 2 after first call

本文关键字:调用 返回 第一次 响应 Ajax      更新时间:2023-09-26

我正在尝试使用Ajax从我的数据库中获取更新的num
主要功能是:

function checkInvitations() {
    if (username ="-1") {
        username = document.getElementById("username").value;
    }
    req.open('GET', 'check_num_of_invitations.php?username='+username);
    req.onreadystatechange = handleNumOfInvitationsResponse;
    req.send(null);
}

函数是从HTML文件中调用的
被调用函数(handleNumOfInvitationsResponse):

function handleNumOfInvitationsResponse() {
if(req.readyState == 4) {
    // update div in HTML
} else {
    // update div in HTML
}
setTimeout(function(){checkInvitations();}, 5000);

}

请注意对checkInvitations的递归调用。

第一次尝试时,响应返回4,一切正常,然后返回2。
感谢

我在InternetExplorer9中遇到了类似的问题,我通过在查询字符串中添加时间戳来解决它:

 var url = 'check_num_of_invitations.php?username='+username+'&timestamp='+Date.now();
 req.open('GET', url);