简体   繁体   中英

How to make web page display only recent update rather than reload using AJAX

I made a table on my web page, that reloads every ten seconds to get new information inputted by users, if any. The thing is, I don't want the whole table to reload every ten seconds, I just want the table to display only new updates that are not on the table already. Below is the code I used for reloading the page.

function process(xmlHttp, i) {
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
    //value = encodeURIComponent( objRef.value );
    xmlHttp.open("GET", "php/AjaxBody.php?value=" + i, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send(null);
  } else {
    alert("Hold on");
  }
}

function handleServerResponse() {
  if (test.readyState == 1 || test.readyState == 2 || test.readyState == 3) {}
  if (test.readyState == 4) {
    if (test.status == 200) {
      txtResponse = test.responseText;
      bodyDiv = document.getElementById("body");
      bodyDiv.innerHTML = txtResponse;
    } else {
      alert("Error with the xmlHttp status");
    }
  }
  /*
    else{
        alert("Error with the xmlHttp readystate: " + x.status);
    } */
}

The txtResponse returns the whole table that is reloaded onto the div = body , I would like to know how to go about this, and I would also like it to be native JavaScript ("I don't mind XML, to change the way the information is returned")

I think you can add the limit in your url. Something like this should work fine.

function process(xmlHttp, i, max_id) {
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
    //value = encodeURIComponent( objRef.value );
    xmlHttp.open("GET", "php/AjaxBody.php?value=" + i + "&max_id=" + max_id, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send(null);
  } else {
    alert("Hold on");
  }
}

You could also add a datetime to your objects like a created date and a last modified date. Then do some checks and see if something is new.

Have a look at the javascript framework KnockoutJS if you want to some very complex changetracking, it does a lot for you but it has a relatively high learning curve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM