我正在尝试更新数据库,同时用户关闭浏览器/点击。我尝试使用onbeforeunload函数及其工作正常,但即使在页面刷新。这是代码我试过的
MyJSP:
<script type="text/javascript">
var refresh=false;
$(window).keydown(function(event){
if(event.keyCode==116)
{
refresh=true;
}
})
$(window).on('beforeunload', function(){
if(refresh==false)
{
$.get("BrowserCloseServlet", function() {
});
}
});
</script>
MyServlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
@SuppressWarnings("unused")
String getId = request.getParameter("getid");
Connection con = null;
PreparedStatement pst = null;
PreparedStatement pst2 = null;
ResultSet rst = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5", "root", "");
String query = "select NoOfCount from tbl_BroserCloseTable ";
String query2 = "update tbl_BroserCloseTable set NoOfCount= ? where Sno= ?";
// Statement st = con.createStatement();
// st.executeUpdate("");
pst = con.prepareStatement(query);
rst = pst.executeQuery(query);
if (rst.next()) {
int count = rst.getInt(1);
System.out.println("Actuall count is :" + count);
count -= 1;
pst2 = con.prepareStatement(query2);
pst2.setInt(1, count);
pst2.setInt(2, 1);
pst2.executeUpdate();
System.out.println("Updated successfully...");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
con.close();
rst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
它的工作正常(单击f5按钮时不更新数据库)但如果用户单击刷新按钮,则调用该servlet页面并更新DB.I想在浏览器中单击刷新按钮时停止调用onbeforeunload。
更新:
我只想知道在浏览器中点击刷新按钮时如何使刷新= false; 。
如何做到这一点?