我的数据库中有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
,但无法发布到控制器。
答案 0 :(得分:0)
您在行动中使用$_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,
]);
}
}