简体   繁体   English

每次刷新页面时运行的JSP函数

[英]JSP function running every time page is refreshed

I want to add an item to a shopping basket only the first time the user clicks "add to basket" however every time i refresh the page it adds it again. 我只想在用户第一次单击“添加到购物篮”时将其添加到购物篮中,但是每次我刷新页面时,它都会再次添加它。

Here is my code that adds the item to the basket 这是我的代码,将商品添加到购物篮

    <%
    String empty = request.getParameter("emptyBasket");
    if (empty!=null) {
        basket.clearBasket();
    }

    String item = request.getParameter("addItem"); %>

<script>
    window.onload = function(){
        if(localStorage.getItem("notFirstTime") == null) {
            <% basket.addItem(item); %>
            localStorage.setItem("notFirstTime", true);
        }
    }
</script>

<html>
<body> ....

As you can see I have tried using the window.onload method but it does not work for some reason. 如您所见,我已经尝试使用window.onload方法,但是由于某些原因它无法正常工作。 Let me know if you need to see any more code and i will update. 让我知道是否需要查看更多代码,我将进行更新。

Thanks 谢谢

JSP runs on the server. JSP在服务器上运行。 JavaScript runs on the browser. JavaScript在浏览器上运行。 Server-side code runs first on the server to generate the page. 服务器端代码首先在服务器上运行以生成页面。 Then it sends it over the network to the browser where it runs JavaScript. 然后,它通过网络将其发送到运行JavaScript的浏览器。 basket.addItem(item) will always run as part of the page-generation process since it's server-side code. basket.addItem(item)始终是页面生成过程的一部分,因为它是服务器端代码。

You might want to consider cookies (for anonymous users) or the DB (for authenticated users) for storage of these values. 您可能要考虑使用cookie(对于匿名用户)或DB(对于经过身份验证的用户)存储这些值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM