2016-03-08 60 views
0

有點問題。我想在瀏覽器或標籤關閉時執行查詢,但是如果該頁面中存在任何按鈕或鏈接,並且我點擊其中的任何一個,那麼查詢也會執行。 。需要幫助這僅當瀏覽器關閉時才執行查詢

First.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1 
/jquery.min.js"></script> 

<script type="text/javascript"> 

$(document).bind('keypress', function(e) { 
    if (e.keyCode == 116){ 
     validNavigation = true; 
    } 
    }); 

    // Attach the event click for all links in the page 
    $("a").bind("click", function() { 
    validNavigation = true; 
    }); 

    // Attach the event submit for all forms in the page 
    $("form").bind("submit", function() { 
    validNavigation = true; 
    }); 

    // Attach the event click for all inputs in the page 
    $("input[type=submit]").bind("click", function() { 
    validNavigation = true; 
    }); 

window.addEventListener("beforeunload", function (e) { 
if (!validNavigation) { 
$.ajax({ 
url: 'logout.php', 
type: 'POST', 
async: false, 
timeout: 4000 
}); 
} 
}) 
</script> 

logout.php

<?php 
$username = "root"; 
$password = ""; 
$hostname = "localhost"; 

$dbhandle = mysql_connect($hostname, $username, $password) 
or die("Unable to connect to MySQL"); 
echo "Connected to MySQL<br>"; 


$selected = mysql_select_db("examples",$dbhandle) 
    or die("Could not select examples"); 

$result = mysql_query("DELETE FROM cars WHERE id='1'"); 
mysql_close($dbhandle); 
?> 
+1

究竟有什麼啊你的問題? –

+0

當用戶關閉瀏覽器時,我想執行刪除查詢。使用onbeforeload函數我可以實現它,但問題是查詢執行時,我按下按鈕或單擊鏈接。我只想在瀏覽器關閉時執行查詢 –

+0

http://stackoverflow.com/questions/1631959/how-to-capture-the-browser-window-close-event –

回答

0

事件 「beforeunload」 的時候,瀏覽器卸載當前文檔被觸發。如果您在同一頁面上使用表單,則需要在按下提交時取消設置該事件。

例如像這樣:

<form onsubmit="cancelUnloadAndSubmit()"> 
    Enter name: <input type="text"> 
    <input type="submit"> 
</form> 
0

包住單擊處理像這樣: window.onbeforeunload=null;

可以在onsubmit處理這樣做

<script type="text/javascript"> 
    var validNavigation = false; 
    $(document).ready(function() { 

    $("a").click(function() { 
     validNavigation = true; 
    }); 

    }); 

window.addEventListener("beforeunload", function (e) { 
    if (!validNavigation) { 
    // do something... 
    } 
}) 
</script>