2011-12-06 93 views
12

現在我有一個表單,用戶輸入信息。它比處理bu jQuery ajax函數並設置爲return false;,因此在用戶提交表單後不會發生頁面重新加載。 儘管我需要重新加載頁面,但是如果我刪除return false;,它會在顯示成功消息(此消息在用戶提交數據後顯示)之前刷新頁面。顯示消息後重新加載頁面,jQuery

 $.ajax({ 
     type: "POST", 
     url: "scripts/process.php", 
     data: dataString, 
     success: function() { 
     $("#st_message").html("<p> Your article was successfully added!</p>"); 
     //I need to reload page after the above message is shown 
     } 
    }); 
    return false; 

因此,如何能我重裝頁面顯示的<p> Your article was successfully added!</p>消息後,有輕微的延遲說2 - 3秒,使用戶可以真正閱讀的消息。

回答

22

你可以通過使用setTimeout()函數添加延遲,使得as:

// This will reload the page after a delay of 3 seconds 
window.setTimeout(function(){location.reload()},3000) 

爲了你的需求:

$.ajax({ 
     type: "POST", 
     url: "scripts/process.php", 
     data: dataString, 
     success: function() { 
      $("#st_message").html("<p> Your article was successfully added!</p>"); 
      window.setTimeout(function(){location.reload()},3000) 
     } 
}); 
return false; 

Working Example

+0

由於某種原因,它doesn不工作,可能是因爲回報錯誤? – Ilja

3

喜歡的東西就做:

function delayedRedirect(){ 
    window.location = "/index.php" 
} 

setTimeout('delayedRedirect()', 3000) 

setTimeout用來延遲重定向函數調用,在這種情況下,您可以某處重定向到一個新的URL(以防萬一你需要太)。

否則使用location.reload()重新加載頁面。

2

你的意思是這樣的:window.location.reload()在JavaScript

+0

由於某種原因它不起作用,可能是因爲返回錯誤? – Ilja

2

在代碼中使用

setTimeout("window.location='yourpage.php'",3000); 

給它:

$.ajax({ 
     type: "POST", 
     url: "scripts/process.php", 
     data: dataString, 
     success: function() { 
     $("#st_message").html("<p> Your article was successfully added!</p>"); 
     setTimeout("window.location='yourpage.php'",3000);//reload after 3 sec. 
     } 
     }); 
return false; 
+0

由於某種原因它不起作用,可能是因爲返回錯誤? – Ilja

+0

我試着在這裏重定向代碼和它的工作正常.. – mithunsatheesh

+0

由於某種原因,我需要在$(「#st_message」).tm之前添加它...現在它的作品謝謝))) – Ilja

1

使用setTimeout方法來獲得延時,reload方法重新加載頁面。請注意0​​調用中的true參數,以確保頁面實際上已重新載入,而不是僅從緩存重新繪製。

window.setTimeout(
    function(){ 
    location.reload(true) 
    }, 
    3000 
); 
+0

由於某種原因它不起作用,可能是因爲返回錯誤? – Ilja

+0

不,這隻能是一個問題,如果你試圖立即重新加載頁面。另外,改變另一條評論中提到的代碼的順序也不會有什麼區別。也許是一個錯字? – Guffa

1
$.ajax({ 
    type: "POST", 
    url: "scripts/process.php", 
    data: dataString, 
    success: function() { 
    var miliseconds = 2000; 

    $("#st_message").html("<p> Your article was successfully added!</p>"); 
    setTimeout("window.location=window.location", miliseconds); 
    //I need to reload page after the above message is shown 
    } 
}); 
1
<script type="text/javascript"> 
// 
//your action here 
// 
window.setTimeout(function(){self.parent.location="?list"},3000);//after 3 sec go to (?list or example.html page) 
return false; 
</script> 
1

使用超時是一個非常糟糕的主意。

相關問題