简体   繁体   中英

Refresh page after function has been called

Is there a way that I can run a function then call window.location.reload() to refresh the page? Currently when I do this the page is refreshing but the function isn't running.

function postComment() {
   var name;
   if (document.getElementById("yourName").value == "") {
      name = "(Anonymous)";
   } else  {
      name = document.getElementById("yourName").value;
   }
   var uri = "http://tgg.tcs.com/AP/Open/Service.svc/comment?name=" + name;
   var xhr = new XMLHttpRequest();
   xhr.open("POST", uri, true);
   xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8")

   xhr.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        alert(xhr.responseText);
    }
   }
   xhr.send(JSON.stringify(document.getElementById("comment").value));

}

You need to use a callback

function yourFunction(arg, callback) {
    doSomeStuff(arg);
    callback();
}

yourFunction('argument', window.location.reload);

If doSomeStuff function is async, you have to do

function yourFunction(arg, callback) {
    doSomeStuff(arg, callback);
}

yourFunction('argument', window.location.reload);

also, if you refresh the page, you will refresh the scripts as well, so it depends on what does your function do, you may need a cookie if the data the function generates has to be persistant

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