无法将数据从视图发布到Yii2中的控制器 [英] Unable to post the data from view to controller in Yii2

查看:85
本文介绍了无法将数据从视图发布到Yii2中的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Yii2.我有一个带有复选框的gridview,并单击一个按钮,我正在使用ajax将其重定向到动作控制器.

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.

 <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>

<?php Pjax::begin(); ?>    
        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [


        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],


        'ref_no',
        'dept_code:ntext',
        'dept_name:ntext',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'diconnected_at',
        'reconnected_at',
        'active_energy_total_m',


        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
<?php Pjax::end(); ?>

JS

<?php

$DCOurl = Url::toRoute(['/hecolog/dco']);

$script = <<< JS
$(document).ready(function () {  



 //DCO 
 $('#dco').on('click',function(e) {


       e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

});       

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


 });
});
JS;
$this->registerJs($script, static::POS_END);
?>

但是当我单击断开连接按钮时,它不会重定向到我的控制器.在控制台中,它给了我Not Found (#404): Page not found.

But when I click on the disconnect button it doesn't redirect to my controller. In console it gives me Not Found (#404): Page not found.

更新1

我已经更新了ajax调用,如下所示

I have updated the ajax call like below

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

控制器

 public function actionDco()
{
    if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

        var_dump($data);
        die();
    }
    else{
        $this->redirect('index');
    }




}

按照建议更新代码后,我可以进入控制器,但仍然无法获取数据

After updating the code as suggested I am able to go into my controller but still not able to get the data

在控制台中出现错误Uncaught SyntaxError: Invalid regular expression flags

更新2

下面是我的视图的代码

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\web\JqueryAsset;
/* @var $this yii\web\View */
/* @var $searchModel common\models\HescologSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'DCO / RCO';
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="content-header">
<h1>DCO / RCO List</h1>
</section>
<section class="content">
<div class="box">
    <div class="box-body">


<p>

    <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
    <?= Html::a('Re-Disconnect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>
</p>

 <?php Pjax::begin(); ?>
        <div class="pre-scrollable">
        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [


        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],


        'ref_no',
        'dept_code:ntext',
        'dept_name:ntext',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'diconnected_at',
        'reconnected_at',
        'active_energy_total_m',


        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
        </div>
<?php Pjax::end(); ?>

    </div>
</div>
</section>
<?php

$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);

$script = <<< JS
$(document).ready(function () {      
//DCO 
 $('#dco').on('click',function(e) {


       e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

});



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


 });

 $('#rco').on('click',function(e) {

 e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

  });

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

 });    
 JS;
 $this->registerJs($script, static::POS_END);
 ?>

我一定在做我不理解的错误

I must be doing something wrong which I am not understanding

任何帮助将不胜感激.

Any help would be highly appreciated.

推荐答案

首先url:'$DCOurl'是正确的,并且url必须为单个或 双引号.因此您遇到一个未找到问题:

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

  • 您的项目是htdocs还是www,然后是/inventory-web/backend/?还是还有其他目录?您使用相对网址,因此该网址适用于例如:localhost/inventory-web/backend/web/ ...
  • ajax类型"POST"(如果已设置)应与behaviors ['verbs'] ['actions']相匹配
  • 检查控制器文件名,类名和名称空间
  • 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

这篇关于无法将数据从视图发布到Yii2中的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆