Unable to post the data from view to controller in Yii2

前端 未结 2 962
天涯浪人
天涯浪人 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;
           }
        }
     });
    
    0 讨论(0)
  • 2020-12-07 04:01

    first of all url:'$DCOurl' is correct and url must be in single or double quotation. so you have a not found problem:

    • is your project in htdocs or www followed by /inventory-web/backend/ or there are some more directories? you use relative url so the url would be for ex: localhost/inventory-web/backend/web/ ...
    • ajax type 'POST' should match with behaviors['verbs']['actions'] if you have set it
    • check controller file name, class name and namespace
    0 讨论(0)
提交回复
热议问题