Javascript在函数操作后重新加载


Javascript reload after function action

我有一个网页,有许多复选框,点击时调用Javascript函数:

<input type='checkbox' name='Box[]' value='3313' id='chk_3313' onclick='UpdateRecord(3313, this.checked);' >

Javascript函数:

function UpdateRecord(uid, chk) {
chk = (chk==true ? "1" : "0");
var url = "update_db.php?qso_id="+uid;
if(window.XMLHttpRequest) {
   req = new XMLHttpRequest();
} else if(window.ActiveXObject) {
   req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url, true);
req.send(null);
}

我希望每次选中一个框时刷新网页。通过在函数末尾添加location.reload(),页面被重新加载,但不再调用update_db.php页面。如何在记录更新后重新加载页面 ?

您应该通过回调函数来实现:

function UpdateRecord(uid, chk) {
    chk = (chk==true ? "1" : "0");
    var url = "update_db.php?qso_id="+uid;
    if(window.XMLHttpRequest) {
       req = new XMLHttpRequest();
    } else if(window.ActiveXObject) {
       req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    // Add an event listener to this request
    req.onreadystatechange = function(){
        // Check if the request is ready and didn't return any errors
        if (req.readyState == 4 && req.status == 200) {
            // Reload the page
            document.location.reload();
        }
    }
    req.open("GET", url, true);
    req.send(null);
}