You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态生成表单触发意外POST请求,致ProductsController/view_cart 403错误

购物车数量更新后意外触发POST请求导致403错误

场景代码

1. 页面跳转按钮(dashboard_view.php)

<a class="show_cart" href="<?=base_url('ProductsController/view_cart');?>">Cart (0)</a>

2. 控制器视图加载方法

public function view_cart() {
    $this->load->view('customer/cart_view');
}

3. 前端流程代码

步骤1:AJAX加载购物车商品并生成表单(cart_view.php)

$(document).ready(function() {
    getCartProducts();
    processProductQuantityForm();

    function getCartProducts() {
        $.ajax({
            url: "<?=base_url('ProductsController/getCartProducts');?>",
            type: 'GET',
            dataType: 'json',
            success: function(response) {
            $.each(response.cart_items, function(index, cart) {
                let cartItem = `<form action="" class="product" method="post">
                                    <input type="hidden" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">
                                    <input type="hidden" name="cart_id" value="${cart.cart_id}">
                                    <input type="text" class="csrf" value="123">
                                    <ul>
                                        <li>
                                            <img src="<?=base_url('${cart.image_url}');?>" alt="">
                                            <h3>${cart.name}</h3>
                                            <span>₱${cart.price}</span>
                                            <ul>
                                                <li>
                                                    <label>Quantity</label>
                                                    <input type="text" min-value="1" id="quantity" data-cart_id="${cart.cart_id}" value="${cart.quantity}" name="quantity">
                                                    <!--NOTE: This is the button that triggers the submit-->
                                                    <ul>
                                                        <li><button type="button" class="increase_quantity" data-quantity-ctrl="1"></button></li>
                                                        <li><button type="button" class="decrease_quantity" data-quantity-ctrl="0"></button></li>
                                                    </ul>
                                                </li>
                                                <li>
                                                    <label>Total Amount</label>
                                                    <span class="total_amount" data-price="${cart.price}" id="total_amount">₱${cart.total_amount}</span>
                                                </li>
                                                <li>
                                                    <button type="button" class="remove_item"></button></li>
                                            </ul>
                                                <div>
                                                    <p>Are you sure you want to remove this item?</p>
                                                    <button type="button" class="cancel_remove">Cancel</button>
                                                    <button type="button" class="remove">Remove</button>
                                                </div>
                                        </li>
                                    </ul>
                                </form>`;
                        $('.cart_items_form').append(cartItem);
                    });
                    updateProductQuantity();
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX Error:', textStatus, errorThrown);
                }
            });
        }
});

步骤2:点击增减按钮提交表单触发AJAX更新数量

function updateProductQuantity() {
    $('.product').on('click', '.increase_quantity, .decrease_quantity', function() {
        let quantityInput = $(this).closest('form').find('#quantity');
        let quantity = quantityInput.attr('value');
        let newValue;

        if ($(this).hasClass('increase_quantity')) {
            quantityInput.attr('value', function(index, oldValue){
            newValue = parseInt(oldValue, 10) + 1;
                return newValue;
            });
        } else if (quantity > 1) {
            quantityInput.attr('value', function(index, oldValue) {
                newValue = parseInt(oldValue, 10) - 1;
                return newValue;
            });
        }
        /*Submit the form when these buttons are clicked, containing the new quantity, csrf token and cart id*/
        $(this).closest('.product').submit();
        updateTotal(quantityInput);
    });
}

步骤3:AJAX成功后更新CSRF Token

function processProductQuantityForm() {
    $('.cart_items_form').on('submit', '.product', function(e) {
        e.preventDefault();
        let formData = new FormData(this);
        $.ajax({
            url: "<?=base_url('ProductsController/processProductQuantityForm');?>",
            type: 'POST',
            dataType: 'json',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                console.log(response);
                $(".csrf").val(response.result.newCsrfToken);
                $("input[name='<?= $this->security->get_csrf_token_name() ?>']").val(response.result.newCsrfToken);
                    },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('AJAX error:', textStatus, errorThrown);

            }
        });
    })
}

问题描述

成功更新商品数量(前端显示与数据库操作均正常)后,会意外触发对http://localhost/thrifted-threads/ProductsController/view_cart的HTTP POST请求,导致403 Forbidden错误,无法确定该请求的触发原因。

内容的提问来源于stack exchange,提问作者Adrian Gaile Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 04:59:55