Unable to post the data from view to controller in Yii2

前端 未结 2 963
天涯浪人
天涯浪人 2020-12-07 02:59

I am working on Yii2. I have a gridview with checkbox and on a button click I am redirecting it to an action controller using ajax.



        
2条回答
  •  一生所求
    2020-12-07 03:38

    First, if you're serving an Ajax request you cannot do a redirect:

    public function actionDco()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $rv=[];
        if(Yii::$app->request->isAjax && Yii::$app->request->post())
        {
            $data = explode(',',$_POST['data']);
    
            $rv["infos"]=$data;
            $rv["status"]='gotData';
        }
        else{
            $rv["url"]=Url::to('index');
            $rv["status"]='redirect';
    
        }
        return $rv;
    }
    

    About the JS error, instead of:

    $.ajax({
        url: $DCOurl,
        type: 'POST',
        dataType: 'json',
        data: {data:strValue},         
        success: function(data) {
           alert(data);
        }
     });
    

    Add the quotes aroun the $DCOurl and to manage the return value from the ajax call

    $.ajax({
        url: "$DCOurl",
        type: 'POST',
        dataType: 'json',
        data: {data:strValue},         
        success: function(data) {
           if(data.status=='gotData'){
               alert(data.infos);
           }
           if(data.status=='redirect'){
               window.location.href=data.url;
           }
        }
     });
    

提交回复
热议问题