商品点击加入购物车不跳转

问题遇到的现象和发生背景

点击加入购物车不跳转

问题相关代码,请勿粘贴截图
 <div class="goods_num">
                <label>购买数量:</label>
                <span><input type="text" value="1" id="good_nums" class="good_nums" /></span>
            </div>
            <div style="padding:20px 0;">
                <span><a href="javascript:void(0)" id="cart_goods" class="goods_sub goods_sub_gou" >加入购物车</a></span>
            </div>

<script>
    $("#cart_goods").click(function () {
        //1.获取productid,购买数量
        var productId=${requestScope.Product.id};
        var quantity=$("#good_nums").val();
        //3.发送给服务器
        $.post("${pageContext.servletContext.contextPath}/cart",{
            productId:productId,
            quantity:quantity,
            action:"add"
        },function (data) {
            if (data==0){
                window.location.href="${pageContext.servletContext.contextPath}/login";
            }
            else if (data==1){
                window.location.href="${pageContext.servletContext.contextPath}/cart";
            }
        });

    });
</script>

运行结果及报错内容

浏览器控制台报错

jquery.js:142
POST http://localhost:8080/mystore1_war_exploded/cart 405
ajax @ jquery.js:142
post @ jquery.js:135
(匿名) @ goods?productId=2:272
handle @ jquery.js:64
o @ jquery.js:57



我想要达到的结果

点击加入购物车后跳转购物车页面

   var productId="${requestScope.Product.id}";  //${requestScope.Product.id}最好是放到引号里
  你$.post()发送给服务器的 http://localhost:8080/mystore1_war_exploded/cart 地址是405错误. 应该是你服务器的问题.不是这个代码的问题

img


这边这句话,有问题哟,你需要把双引号改成号才行,双引号是直接将路径当成了字符串,使用才会讲你${}当成变量输出

"${pageContext.servletContext.contextPath}/cart"
改成
//1.第一种方式
`${pageContext.servletContext.contextPath}/cart`
//第二种方式
pageContext.servletContext.contextPath+"/cart"

有帮助请点一个采纳哟

img

${**}/**”出现的地方改成`${**}/**`

有帮助请点一个采纳哟