<input type="button" name="buy" value="购买" onclick="shopcart();" />
      <script type="" language="javascript">function shopcart(){
        <% Vector vecid = (Vector)session.getAttribute("goodid");
           if(vecid!=null){
             if(!vecid.contains(Integer.toString(gid))){
                 vecid.add(Integer.toString(gid));
                 session.setAttribute("goodid",vecid);
             }}else{vecid=new Vector();
                    vecid.add(Integer.toString(gid));
                    session.setAttribute("goodid",vecid);} %>
           location.href="shoppingcart.jsp";}</script>小弟用如上代码实现把商品放入购物车的功能,但是其中java代码是打开页面就会执行,怎么能控制为按了“购买”按钮后才执行?

解决方案 »

  1.   

    JAVA代码是在服务器端执行的JS代码是在客户端执行的你如果点了购买按钮那么只能调用JS代码无法直接代用JAVA代码的这个是JSP的原理来限制的无法进行修改购物车你不妨用AJAX技术来实现下我做的时候是如果对方点了购买的话就直接跳到了购买页面显示出这个物品的详细信息然后输入购买的数量再提交到服务器上然后在服务器端那里写入SESSION实现购物车功能