Error in accessing post json data in yii2

2019-04-11 17:08发布

问题:

Am passing data to yii2 using ajax request but i keep on getting a 500 error

This is the ajax request code:

<?php 
 $script = <<< JS

     $('form#forward_pr').on('beforeSubmit', function(e){
    var keys = $('#grid').yiiGridView('getSelectedRows');
     $.post({
       url: "forwardpr", // your controller action
       dataType: 'json',
       data: {keylist: keys},
       success: function(data) {
          alert('I did it! Processed checked rows.')
       },
     error: function(err){
       console.log("server error");
       }
    });
       return false;
    }  ) ;

    JS;
    $this->registerJS($script);
 ?>

When i do console.log(keys) this returns

[0, 1]

This is my controller code:

if (Yii::$app->request->post()) {
         echo $post = json_encode($_POST['keys']);
          if (isset($_POST['keylist'])) {
                $keys = \yii\helpers\Json::decode($_POST['keylist']);
              print_r($keys);
            }else{
              echo "1";
          }

The above always executes the error part of post request, What could be wrong;

回答1:

You are sending your JSON as encoded (post) data body, not key value pairs. So your approach is not working this way.

There are two options to fix this:

  1. refactor your controller into a RESTful service
  2. in your controller use the JSON body rather than POST parameters

While the first option is preferred in the long run, the second option is pretty simple as a quick fix.

First, make sure you configure your app to parse JSON body conten. IN config.php add this to the components array:

'request' => [
    'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ]
]

Then in your controller use this to get the JSON parameters:

$model->load(Yii::$app->getRequest()->getBodyParams());


回答2:

I'm a newbie.. But I also want use checkboxcoloumns in gridview (Kartik version). 1st thing.

Instead of writing

var keys = $('#grid').yiiGridView('getSelectedRows');

I have to write

var keys = $('#w4').yiiGridView('getSelectedRows');

2nd thing. In the controller you can process the keylist, but don't try to decode it, simple use it int this way:

        $keys = $_POST['keylist'];

and it seems it works for me!

Sorry for my english..