在yii2中使用ajax更改状态活动/非活动状态

时间:2014-09-16 05:44:48

标签: ajax yii2

[
    'attribute' => 'status',
    'format' => 'html',
    'value' => function ($data) {
        if($data->status==true) {
            return Html::a("Inactive", "#", ['id' => $data->id, 'class' => 'a_status']);                    
        }
        else {
            return Html::a("Active", "#");
        }
]

问题是,此代码未在链接中返回“id”属性。那么,想知道这是否是将链接置于网格视图中的当前方式,还是有人能指出我正确的方式?'

提前谢谢。

2 个答案:

答案 0 :(得分:0)

您的代码缺少一个右括号和format键值的变化 -

尝试 -

[
    'attribute' => 'status',
    'format' => 'raw',                //It was 'html' before
    'value' => function ($data) {
        if($data->status==true) {
            return Html::a("Inactive", "#", ['id' => $data->id, 'class' => 'a_status']);                    
        }
        else {
            return Html::a("Active", "#");
        }
    }                                 //missing parenthesis
] 

答案 1 :(得分:0)

嗯,你错过了很多代码。以下是一些观察结果。

*)我对列

使用这种定义
'value'=>function ($model, $key, $index, $widget) {

我不确定它是否有所作为,尝试这种方式也许这就是问题所在。

其他事项:
*)你为什么要使用return

Html::a("Inactive", "#", ['id' => $data->id, 'class' => 'a_status']);

而不是

Html::a("Inactive", ['change-status', 'status' => 'active', 'id' => $data->id], ['class' => 'a_status']);

您正在以这种方式创建与正确网址的链接。如果有人没有启用javascript,它仍然适用于他们,只需刷新。

现在您可以创建一个全局的ajax函数,您可以轻松地重用更多屏幕。

现在actionChangeStatus函数可以像这样结束

if(Yii::$app->request->getIsAjax()) {
    Yii::$app->response->format = 'json';
    return ['success' => true];
} else {
    return $this->redirect(['index']);
}

我的ajax看起来像这样

jQuery.ajax({
            "type": "GET",
            "url": element.attr('href'),
            "cache": false,
        })
        .success(function ( response ) {
            $.pjax.reload({container: "#main-pjax", async:false, timeout: 4000});
        });