Introduction: I have nothing to do this weekend, so I remembered a B2C e-commerce platform I built earlier. There are still some areas that are not perfect, so I thought about improving it. Well, the problem is this, in e-commerce There is a scenario in the platform where I place the shopping cart in the Session so that it can get the shopping cart model from the Session during the entire shopping process. The products I have in a certain type of shopping cart will be reduced in the database. The quantity purchased in the shopping cart, but if I close the window, how can I add the quantity of goods in the shopping cart model in the Session to the database? So I searched GOOGLE and Baidu, and the first prompt I got was: close the window automatically Clear the Session, so the first method I found was to use the onunload attribute on the tag and call a certain js such as: This method triggers the close() event when the window is closed. , so I can define the method of deleting Session in the close() method...
But this is not the case. Onunload will be triggered when you refresh this page and click on the link on this page, so I went to GOOGLE again , search in Baidu: The answer obtained is as follows:
< script>
window.onunload = function(){if(self.screenTop>9000)alert('This window has been closed!')}
or
< script>
window.onunload = function(){if(self.screenLeft>9000)alert(The window has been closed!.')}
Description:
window.screenTop
Get the y coordinate of the upper left corner of the browser client area relative to the upper left corner of the screen
screenTop> The number following must be greater than the height in your display resolution
For example, 800* 600, this number must be greater than 600
window.screenLeft
Get the x coordinate of the upper left corner of the browser client area relative to the upper left corner of the screen
screenLeft> The number following must be greater than the width in your display resolution
For example, 800*600, this number must be greater than 800
Usually these two values are set to 9000
So I used the above method to achieve that the onunload event is only triggered when the page is closed.
Summary: ① When using the onunload attribute, you can use Ajax to clear the Session, or you can use window.location.href to trigger a request, such as what I am doing here Using struts2, I can use
Then there is a request for closeWindow.action Process the items in the shopping cart in the Session and add their quantity to the database;
② Here I also have Ajax to handle the request, but in fact we only need to process the Session and do not need to process any asynchronous returns after the Session. information, so I still use the method of triggering a request. The final writing method is as follows:
onunload="javascript:if(self.screenTop>9000) window.location.href='${pageContext.request.contextPath }/cart/closeWindow.action';"> ;