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

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

问题描述

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

 <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco'])?><?php Pjax::begin();?><?= GridView::widget(['数据提供者' =>$数据提供者,'过滤器模型' =>$搜索模型,'列' =>[['类' =>'yiigridCheckboxColumn', 'checkboxOptions' =>函数($d){返回 ['值' =>$d['msn']];}],'参考编号','dept_code:ntext','部门名称:ntext','allowed_units','msn','units_consumed',['标签' =>'断开','属性' =>'断开','格式'=>'原始','内容选项' =>['style'='text-align:center'],'价值' =>功能($模型){返回 $model->disconnected == 1 ?'<span class="glyphicon glyphicon-ok text-success"></span>': '<span class="glyphicon glyphicon-remove text-danger"></span>';},'过滤器' =>Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' =>'表单控制']),],'diconnected_at','reconnected_at','active_energy_total_m',['类' =>'yiigridActionColumn'],],]);?><?php Pjax::end();?>

JS

registerJs($script, static::POS_END);?>

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

更新 1

我已经更新了像下面这样的ajax调用

$.ajax({url: $DCOurl,//去掉了引号 ''类型:'POST',数据类型:'json',数据:{数据:strValue},成功:功能(数据){警报(数据);}});

控制器

 公共函数 actionDco(){if(Yii::$app->request->isAjax && Yii::$app->request->post()){$data =explode(',',$_POST['data']);var_dump($data);死();}别的{$this->redirect('index');}}

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

在控制台中我收到错误 Uncaught SyntaxError: Invalid regular expression flags

更新 2

下面是我的视图代码

title = 'DCO/RCO';$this->params['breadcrumbs'][] = $this->title;?><section class="content-header"><h1>DCO/RCO列表</h1></节><section class="内容"><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(['数据提供者' =>$数据提供者,'过滤器模型' =>$搜索模型,'列' =>[['类' =>'yiigridCheckboxColumn', 'checkboxOptions' =>函数($d){返回 ['值' =>$d['msn']];}],'参考编号','dept_code:ntext','部门名称:ntext','allowed_units','msn','units_consumed',['标签' =>'断开','属性' =>'断开','格式'=>'原始','内容选项' =>['style'='text-align:center'],'价值' =>功能($模型){返回 $model->disconnected == 1 ?'<span class="glyphicon glyphicon-ok text-success"></span>': '<span class="glyphicon glyphicon-remove text-danger"></span>';},'过滤器' =>Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' =>'表单控制']),],'diconnected_at','reconnected_at','active_energy_total_m',['类' =>'yiigridActionColumn'],],]);?>

<?php Pjax::end();?>

</节><?php$DCOurl = Url::toRoute(['/hescolog/dco']);$RCOurl = Url::toRoute(['/hescolog/rco']);$script = <<<JS$(document).ready(function () {//数据中心$('#dco').on('click',function(e) {e.preventDefault();var strValue = "";$('input[name="selection[]"]:checked').each(function() {if(strValue!==""){strValue = strValue + " , " + this.value;}别的strValue = this.value;});$.ajax({网址:$DCOurl,类型:'POST',数据类型:'json',数据:{数据:strValue},成功:功能(数据){警报(数据);}});});$('#rco').on('click',function(e) {e.preventDefault();var strValue = "";$('input[name="selection[]"]:checked').each(function() {if(strValue!==""){strValue = strValue + " , " + this.value;}别的strValue = this.value;});$.ajax({url: '$RCOurl',类型:'POST',数据类型:'json',数据:{数据:strValue},成功:功能(数据){警报(数据);}});});});JS;$this->registerJs($script, static::POS_END);?>

我一定是做错了什么,我不明白

任何帮助将不胜感激.

解决方案

首先 url:'$DCOurl' 是正确的并且 url 必须是单个或双引号.所以你有一个未找到的问题:

  • 您的项目是在 htdocs 或 www 中,然后是 /inventory-web/backend/ 还是其他一些目录?您使用相对 url,因此 url 将用于例如: localhost/inventory-web/backend/web/...
  • ajax 类型 'POST' 应该与 behaviors['verbs']['actions'] 相匹配
  • 检查控制器文件名、类名和命名空间

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' => 'yiigridCheckboxColumn', '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' => 'yiigridActionColumn'],
    ],
]); ?>
<?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);
?>

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.

Update 1

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);
    }
 });

Controller

 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

In console I am getting error Uncaught SyntaxError: Invalid regular expression flags

Update 2

Below is the code for my view

<?php

use yiihelpersHtml;
use yiigridGridView;
use yiiwidgetsPjax;
use yiihelpersUrl;
use yiiwebJqueryAsset;
/* @var $this yiiwebView */
/* @var $searchModel commonmodelsHescologSearch */
/* @var $dataProvider yiidataActiveDataProvider */

$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' => 'yiigridCheckboxColumn', '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' => 'yiigridActionColumn'],
    ],
]); ?>
        </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.

解决方案

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

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆