首页 > 解决方案 > yii2中的排序问题

问题描述

我的数据库中有 json 数组 {"dashboard_layout":[10,9,4,5]}

我可以对项目进行排序,但不能更新数据库中的排序值。

    $('#sortable').sortable({
        helper: fixWidthHelper,
        axis: 'y',
        stop: function (event, ui) {
            var data = $(this).sortable('serialize');

            alert(data);
            $('h6').text(data);    // Checks to make sure that data is compiled correctly
            $('h5').text(url);     //  Checks to make sure url is compiled correctly
            $.ajax({
                type: 'post',
                data: data,
                url: '" . Yii::$app->getUrlManager()->createUrl("/site/dashboard-block-sort") . "',                
                dataType: 'json',
                success: function(data){ 
                 alert('hii');
                alert(data.value);
            },
            error: function (xhr, ajaxOptions, thrownError) {
             //  alert(thrownError);
              // console.log(thrownError);

            }
            });
        }
    }).disableSelection();

在我的控制器中

 public function actionDashboardBlockSort(){
     if(isset($_POST['data'])) {
        $dashboardLayout = $_POST['data'];
        $model = \app\models\UserPreferences::find()->where(['user_id' => Yii::$app->user->identity->user_id])->one();
        // check here if model is not null 
        $perferencesOther = json_decode($model->others);


        $perferencesOther->dashboard_layout = $dashboardLayout; 
        // store updated preferencves in db
        $model->others = json_encode($perferencesOther); 
        $model->save(); 

        echo Json::encode([
            'status' => true,
            'value'=>$model->others
        ]); 
    } else {
        echo Json::encode([
            'status' => false,              
        ]);
    }
}

有什么问题吗?当我alert(data)在查看页面时。我得到了正确的排序值,item[]=10&item[]=9&item[]=5&item[]=4但无法发布到控制器。

标签: jqueryajaxyii2

解决方案


您不应该使用$_POST['item']而不是$_POST['data']在您的操作中发布序列化字符串,item[]其中data包含一个 javascript数组var

public function actionDashboardBlockSort(){
     if(isset($_POST['item'])) {
        $dashboardLayout = $_POST['item'];
        $model = \app\models\UserPreferences::find()->where(['user_id' => Yii::$app->user->identity->user_id])->one();
        // check here if model is not null 
        $perferencesOther = json_decode($model->others);


        $perferencesOther->dashboard_layout = $dashboardLayout; 
        // store updated preferencves in db
        $model->others = json_encode($perferencesOther); 
        $model->save(); 

        echo Json::encode([
            'status' => true,
            'value'=>$model->others
        ]); 
    } else {
        echo Json::encode([
            'status' => false,              
        ]);
    }
}

推荐阅读