首页 > 解决方案 > Yii2 使用 Ajax 提交链接

问题描述

我正在尝试在 Yii2 中为我的内容创建投票,所以我尝试使用“a”标签和小部件使用 Ajax 插入数据,但是使用 ajax 它不起作用,没有 ajax 它工作完美。但是当我使用 Ajax 时它不起作用,并且我在控制台中没有错误。我的视图代码是:

<script type="text/javascript">
    $('document').ready(function(){
        $('#btn-vote-up' + <?= $pst_id ?>).on("click", function(e){
            $.ajax({
                type: "POST",
                data: {"value" : "Like"},
                success: function(msg) {
                    console.log (<?= $pst_id ?>);
                    $('#note-up' + <?= $pst_id ?>).load(' #note-up' + <?= $pst_id ?>);
                }               
            });
            e.preventDefault();
        });
    });
</script>


    <?= Html::a('<i class="ly-ic-favorite-plus"></i>', '#', [
                'class' => 'btn-logout',
                'id' => 'btn-vote-up'.$pst_id,
                'data'  => [
                    'params' => [
                        'value' => 'Like',
                        'pstIDL' => $pst_id,
                        ],
                    ],
        ]) ;
    ?>
    <?php yii\widgets\Pjax::begin(['id' => 'note-up'.$pst_id]) ?>
        <span><?= $total_up ?></span>
    <?php yii\widgets\Pjax::end() ?>

我的小部件代码是:

if (Yii::$app->request->post('value') == 'Like')
            {
                $pstIDL = Yii::$app->request->post('pstIDL');

                $modelLIKEPOST = $this->findLikePost($pstIDL);

                AxVotePost::VoteUP($modelLIKEPOST, $this->usr_rid, $this->chn_id, $pstIDL);
                header('Location: ' .Url::current() );
                exit;
            }

标签: ajaxyii2

解决方案


$pstIDL在进行 ajax 调用时没有发送值,而只是value在发送,您可以使用var data=$(this).data('params')两者来获取pstIDL,并且value json在调用中将其与数据一起发送,请参见下文

<script type="text/javascript">
    $('document').ready(function(){
        $('#btn-vote-up' + <?= $pst_id ?>).on("click", function(e){
           var data= $(this).data('params');
            $.ajax({
                type: "POST",
                data: data,
                success: function(msg) {
                    console.log (<?= $pst_id ?>);
                    $('#note-up' + <?= $pst_id ?>).load(' #note-up' + <?= $pst_id ?>);
                }               
            });
            e.preventDefault();
        });
    });
</script>

推荐阅读