首页 > 解决方案 > renderAjax 无法返回数据

问题描述

我在过去的一年里做了这个,它工作得很好。直到最近我遇到了这个问题,我不知道是什么原因造成的。

在这里,我试图通过(2) ajax javascript(1) 表单传递供应商ID ,并将AdminController 中的 (3) 数据返回到同一视图中的(4)div

(1)形式:-

<?php $form = ActiveForm::begin([
 'id'=>'chatform'
]);?>
<div class="box-body">
 <table id="example1" class="table table-bordered table-striped">
  <thead>
  <tr>
   <th>No</th>
   <th>Supplier</th>
   <th>Option(s)</th>
  </tr>
  </thead>
  <tbody>

  <?php 
  for($x = 0; $x < count($supplierChatInfoListTable); $x++){ ?>  

  <tr>
   <td>
    <?=$x+1?>
    <div class="form-group">
     <input type="hidden" name="supplierID" id="supplierID" class="form-control" 
      value="<?=$supplierChatInfoListTable[$x]['supplierID']?>" style="width: 50px">
    </div>
   </td>
   <td >
    <h4><?=$supplierChatInfoListTable[$x]['supplierFirstname']?></h4>
   </td>
   <td>
    <button type="button" class="btn btn-primary btnchat"><i class="fa fa-edit"></i></button>
   </td>
  </tr>

  <?php } ?>

  </tbody>
  <tfoot>
  <tr>
   <th>No</th>
   <th>Supplier</th>
   <th>Option(s)</th>
  </tr>
  </tfoot>
 </table>
</div>
<?php ActiveForm::end();?>

这是我的(2)javascript在同一视图中运行:-

<?php
$urproudcode= Url::to(['admin/chatinfo2pass']);

$this->registerJs("
 $(function(){
  $('.btnchat').click(function(){
    var supplierID = $('#supplierID').val();
    $.ajax({
      'url':'".$urproudcode."',
      'data':{supplierID:supplierID},
      'method':'POST',
      beforeSend: function (xhr) {
        $.blockUI({
          message: 'Processing...',
          css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
          }
        });
      },
      'success':function(data){
        $('.chatmessages').html('Success');
        if(data == 'false'){
          $.unblockUI();
          $('.chatmessages').html('Data False');
        }else{
          $.unblockUI();
          $('.chatmessages').html(data);
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
        $.unblockUI();
        $('.chatmessages').html('Failed');
        console.log(data);
      }
    });
   });
  });
 ");
?>

(3)div与 class=chatmessages 在同一视图中

<div class="col-md-8 chatmessages">

</div>

(4)AdminController中的actionChatinfo2pass

public function actionChatinfo2pass()
{
    $postData = \Yii::$app->request->post('supplierID');

    $supplierID = intval($postData);

    // fetch all supplier for chat
    $supplierChatInfoListTable = SupplierProfile::find()
    ->select(['supplier_profileID AS supplierID','supplier_profile.first_name AS supplierFirstname', 
    'supplier_profile.middle_name AS supplierMiddlename', 'supplier_profile.last_name AS 
    supplierLastname', 'login_profile.login_profileID AS loginID', 'status_login.status_loginID AS 
    statusLoginID', 'status_login.description AS statusLogindesc'])
    ->leftJoin('login_profile', 'login_profile.login_profileID = supplier_profile.login_profile_ID')
    ->leftJoin('status_login', 'status_login.status_loginID = login_profile.status_login_ID')
    //->where(['=', 'status_login.description', $activeSupplier])
    ->orderBy(['supplier_profile.supplier_profileID' => SORT_ASC])
    ->asArray()
    ->all();

    $dataSend['supplierChatInfoListTable'] = $supplierChatInfoListTable;

    $this->layout = 'admin/main';
    $html= $this->renderAjax('@app/views/admin/displaychatmessage.php',$dataSend);
    echo $html;
}

但它返回两个供应商的“相同”供应商ID,如下所示:

在 ajax 调用中从 displaychatmessage.php 更新了 div 结果

和浏览器控制台给我这个错误?(更新): -

更新了页面加载时的 Ajax 错误消息和单击后的错误

顺便说一句,这是displaychatmessage.php的内容(我只是尝试显示 suppllierID 及其名称)

    <!-- DIRECT CHAT WARNING -->
      <div class="box box-warning direct-chat direct-chat-warning">
        <div class="box-header with-border">
          <h3 class="box-title">Direct Chat</h3>

          <div class="box-tools pull-right">
            <span data-toggle="tooltip" title="3 New Messages" class="badge bg-yellow">3</span>
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Contacts" data-widget="chat-pane-toggle">
              <i class="fa fa-comments"></i></button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <!-- /.box-header -->
        <div class="box-body">
          <!-- Conversations are loaded here -->
          <div class="direct-chat-messages">
            <!-- Message. Default to the left -->
            <div class="direct-chat-msg">
              <div class="direct-chat-info clearfix">
                <?php for($z = 0; $z < count($supplierChatInfoListTable); $z++){?>
                <span class="direct-chat-name pull-left">Supplier ID: <?=$supplierChatInfoListTable[$z]['supplierID']?>, <?=$supplierChatInfoListTable[$z]['supplierFirstname']?> <?=$supplierChatInfoListTable[$z]['supplierMiddlename']?> <?=$supplierChatInfoListTable[$z]['supplierLastname']?></span>
                <?php }?>
                <span class="direct-chat-timestamp pull-right">23 Jan 2:00 pm</span>
              </div>
              <!-- /.direct-chat-info -->
              <img class="direct-chat-img" src="dist/img/user1-128x128.jpg" alt="Message User Image"><!-- /.direct-chat-img -->
              <div class="direct-chat-text">
                Is this template really for free? That's unbelievable!
              </div>
              <!-- /.direct-chat-text -->
            </div>
            <!-- /.direct-chat-msg -->

            <!-- Message to the right -->
            <div class="direct-chat-msg right">
              <div class="direct-chat-info clearfix">
                <span class="direct-chat-name pull-right">Sarah Bullock</span>
                <span class="direct-chat-timestamp pull-left">23 Jan 2:05 pm</span>
              </div>
              <!-- /.direct-chat-info -->
              <img class="direct-chat-img" src="dist/img/user3-128x128.jpg" alt="Message User Image"><!-- /.direct-chat-img -->
              <div class="direct-chat-text">
                You better believe it!
              </div>
              <!-- /.direct-chat-text -->
            </div>
            <!-- /.direct-chat-msg -->
          </div>
          <!--/.direct-chat-messages-->

          <!-- Contacts are loaded here -->
          <div class="direct-chat-contacts">
            <ul class="contacts-list">
              <li>
                <a href="#">
                  <img class="contacts-list-img" src="dist/img/user1-128x128.jpg" alt="User Image">

                  <div class="contacts-list-info">
                        <span class="contacts-list-name">
                          Count Dracula
                          <small class="contacts-list-date pull-right">2/28/2015</small>
                        </span>
                    <span class="contacts-list-msg">How have you been? I was...</span>
                  </div>
                  <!-- /.contacts-list-info -->
                </a>
              </li>
              <!-- End Contact Item -->
            </ul>
            <!-- /.contatcts-list -->
          </div>
          <!-- /.direct-chat-pane -->
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
          <form action="#" method="post">
            <div class="input-group">
              <input type="text" name="message" placeholder="Type Message ..." class="form-control">
                  <span class="input-group-btn">
                    <button type="submit" class="btn btn-warning btn-flat">Send</button>
                  </span>
            </div>
          </form>
        </div>
        <!-- /.box-footer-->
      </div>
      <!--/.direct-chat -->

你能帮我解决这个问题吗?我不知道哪里出错了。

标签: yii2renderajaxform

解决方案


正如您所提到的,您supplierID在单击两个供应商时都会得到相同的结果。这个问题是因为在你的 js 代码中你是supplierID通过输入的 id 获取的'#supplierID',并且根据你的 html 代码,两个供应商的输入元素在他们的 id 属性中具有相同的值,即'supplierID',因为每次Node.js 将从第一个 id 属性值为“supplierID”的输入元素中获取值。所以你需要对你的html和js代码做一些修改。由于每个供应商都有单独的编辑按钮,因此supplierID您可以将其存储在编辑按钮的数据属性中,而不是使用输入来存储值。所以你更新的 html 代码会变成

<?php $form = ActiveForm::begin([
 'id'=>'chatform'
]);?>
<div class="box-body">
 <table id="example1" class="table table-bordered table-striped">
  <thead>
  <tr>
   <th>No</th>
   <th>Supplier</th>
   <th>Option(s)</th>
  </tr>
  </thead>
  <tbody>

  <?php 
  for($x = 0; $x < count($supplierChatInfoListTable); $x++){ 
    $supID = $supplierChatInfoListTable[$x]['supplierID']; ?>  

  <tr>
   <td>
    <?=$x+1?>
    <div class="form-group">
     <input type="hidden" name="<?='supplierID'.$supID?>" id="<?='supplierID'.$supID?>" class="form-control" 
      value="<?=$supID?>" style="width: 50px">
    </div>
   </td>
   <td >
    <h4><?=$supplierChatInfoListTable[$x]['supplierFirstname']?></h4>
   </td>
   <td>
    <button type="button" class="btn btn-primary btnchat" data-supplierID="<?=$supID?>"><i class="fa fa-edit"></i></button>
   </td>
  </tr>

  <?php } ?>

  </tbody>
  <tfoot>
  <tr>
   <th>No</th>
   <th>Supplier</th>
   <th>Option(s)</th>
  </tr>
  </tfoot>
 </table>
</div>
<?php ActiveForm::end();?>

然后supplierID从js中按钮的数据属性中获取点击的供应商。所以你的js代码会变成

<?php
$urproudcode= Url::to(['admin/chatinfo2pass']);

$this->registerJs("
 $(function(){
  $('.btnchat').click(function(){
    var supplierID = $(this).attr('data-supplierID');
    $.ajax({
      'url':'".$urproudcode."',
      'data':{supplierID:supplierID},
      'method':'POST',
      beforeSend: function (xhr) {
        $.blockUI({
          message: 'Processing...',
          css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
          }
        });
      },
      'success':function(data){
        $('.chatmessages').html('Success');
        if(data == 'false'){
          $.unblockUI();
          $('.chatmessages').html('Data False');
        }else{
          $.unblockUI();
          $('.chatmessages').html(data);
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
        $.unblockUI();
        $('.chatmessages').html('Failed');
        console.log(data);
      }
    });
   });
  });
 ");
?>

我希望你的问题能得到解决。


推荐阅读