开发者

scriptlet gets executed wrongly

The following code:

<button type="button" id="button" onclick="<%cart.removeItem(0);%>">Click me</button>

is suppose to be executed when the button is clicked. However,

 "<%cart.removeItem(0);%>"

is being executed when page is refreshed without clicking the button. Why is this happening?

Cheers.

Heres the full source.

   <html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
   </head>
   <body>
    <jsp:useBean id="cart" scope="session" class="myBeans.cart" />
    <%
    cart.addItem("aji", "1000", "1");
    cart.addItem("ewer", "200", "1");
    cart.addItem("dfwerweji", "10", "1");
    cart.addItem("ldsjioi", "1320", 开发者_如何学运维"1");

    String[] prodNames = cart.getProdNames();
    double[] prices = cart.getProdPrices();
    int[] qtys = cart.getProdQtys();
    double total = 0;

    for(int i=0; i<prodNames.length; i++){
    total += prices[i]*qtys[i];
    out.println(prodNames[i]);
    out.println(" " + prices[i] + " ");
    out.println("<input type=text name=newQty value=" + qtys[i] + ">");
    out.println(" " + prices[i] * qtys[i]);
    }
    %>
    <br/>
    <button type="button" id="button" onclick="<%cart.removeItem(0);%>">Click me</button>
    </body>
    </html>


I think you are mixing up your languages here. I suspect that 'cart' is a Java object, and you can only modify JavaScript objects on the client side. You would have to have something like this to make it work:

<script> 
  doRemoveFirst = function() { new Ajax.Request('removeFirst.page'); }; 
</script>
<button type="button" id="button" onclick="doRemoveFirst();">Click me</button>

Then have a page on the server called 'removeFirst' that will remove that object from the Java object (maybe kept in session?) and you can update your page accordingly.

EDIT: Here's an image to help. Everything left of diagonal is client-side, while everything right is server-side.

scriptlet gets executed wrongly

EDIT 2: To remove and fix the page for the user

I would say something like (assuming jQuery) this might work for you.

$(".item-row").first().remove(); 
$(".item-row").each(function(idx, el) {
  var elem = $(el).children().find('.index-cell');
  elem.text(+elem.text() - 1);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜