首页 > 解决方案 > ajax jquery复选框值重复

问题描述

我试着做一个产品比较

1/客户勾选一个或多个比较复选框

2 / 显示复选框时,底部会出现一条消息

3 / 复选框的值存储在会话下

步骤1

下面的脚本与 ajax 有关。每次我单击复选框时,它都会调用 ajax,但是如果我单击,我会收到一条消息,如果我单击另一个我有 2 条消息,如果我单击另一个我有 3 条消息...

第2步

我的目标是改变这一点并制定以下规则:

1 / 选择复选框

2 / 消息显示在底部,带有按钮

3/ 单击按钮,所有值都插入到会话中。

目前,我在第 1 步,现在如何进入第 2 步,js 有点迷失。

我想,我必须在 js 中删除成功并包含类似这样的内容

谢谢你。

<div id="container" style="display:none;"> 
<span class="alert alert-info"><button type="button" class="btn btn-primary"><a href="compare.php">Compare</button></span>
</div>

                $new_prods_content .= '
    <script>
    $(function() {
        $(\'input[type=checkbox]\').change(function(){   
            var chkArray = [];   
            $(\'#container\').html(\'\');

            //put the selected checkboxes values in chkArray[]
            $(\'input[type=checkbox]:checked\').each(function() {
                chkArray.push($(this).val());
            });


            //If chkArray is not empty show the <div> and create the list
            if(chkArray.length !== 0){
                $(\'#container\').show();           
                $.each(chkArray, function(i, val) { 
                    $(\'<p>\').text(chkArray[i]).appendTo(\'#container\');

                     $.ajax({
                        method: \'POST\',
                        url : "http://localhost/shop/ext/ajax/products_compare/compare.php",
                        data : {product_id:chkArray[i]},
                        success : function(resp){
                            alert("Product is added to be compared" );
                        }

                    });               
                });
            }else{
                $(\'#container\').hide();   
                $(\'#container\').html(\'\');
            }
        });
    })             
    </script>';

    echo $new_prods_content;

有关我的 ajax 的信息:

$product_id = (int)$_POST['product_id'];

if(!is_array($_SESSION['ids'])) {
  $_SESSION['ids'] = [];
} else {
  array_push($_SESSION['ids'], $product_id);
}

标签: phpjqueryajax

解决方案


推荐阅读