jquery - 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
但无法发布到控制器。
解决方案
您不应该使用$_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,
]);
}
}
推荐阅读
- python - 如何通过python循环修改xml文件中的单个属性而不覆盖整个文件?
- sql-server - 我在哪里可以配置“默认服务器设置”?
- docker - 如何检查 Kubernetes 集群中剩余的内核数和内存容量
- c - C程序查询
- python - 基于列值的熊猫列转换比迭代更快?
- java - Azure Synapse - 如何检索元数据信息以通过 JDBC 生成我自己的 CREATE TABLE 语句
- probability-density - 概率-最大似然/图论
- android - mutableList() 的值更改时不会发生重组
- android - Hilt Android 可以在不同的活动中允许不同的视图模型实例吗?
- r - 如何将类应用于闪亮的动作按钮?