2015-10-08 122 views
0

有沒有辦法讓我可以運行一個函數然後調用window.location.reload()刷新頁面?目前,當我這樣做的頁面刷新,但功能沒有運行。函數調用後刷新頁面

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)); 

} 
+1

當然,但是你需要告訴我們這個功能的作用以及你怎樣稱呼他們。如果它是ajax,那是異步的,如果沒有正確地調用序列,你會中止ajax – charlietfl

+0

基本上我正在做的是使用'XMLHttpRequest()'發佈一條評論,我相信它是異步的... – M0rty

+0

這正是我懷疑......'ajax'是'XMLHttpRequest'的通用術語。需要向我們展示您的代碼 – charlietfl

回答

0

你需要使用一個回調

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

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

如果soSomeStuff功能是異步,你必須做

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

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

另外,如果你刷新頁面,你會刷新腳本所以它取決於你的函數做什麼,如果函數產生的數據必須持久,你可能需要一個cookie