【问题标题】:renderAjax failed to return datarenderAjax 无法返回数据
【发布时间】:2020-01-01 09:44:29
【问题描述】:

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

这里我试图通过 (2)ajax javascript(1)form 传递 supplierID 并返回 (3)数据从 AdminController 到同一视图中的 (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,如下所示:

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

顺便说一句,这是 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 -->

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

【问题讨论】:

  • 从您的代码看来,您的 Ajax 请求引发了一些错误。您可以在浏览器控制台中检查错误或使用您的代码查看错误消息。检查如何在浏览器控制台中查看 Ajax 错误 here. 或检查如何使用您的代码查看错误消息 here。在您的问题或评论中添加 Ajax 错误消息和错误代码以获得进一步的帮助。
  • @MAZ,我已经按照您的建议添加了 Ajax 错误消息(在问题部分)。我应该从这里做什么?
  • 您是否在单击按钮之后或之前(在页面加载时)收到此错误?你用的是哪个 jQuery 版本?
  • @MAZ,页面加载时更新的 Ajax 错误已粘贴在上面的问题部分中。你可以看看它。它给了我期望参数 1 是数组,给定整数。这是什么意思?
  • 嘿@MAZ。我已经得到它来返回数据!我没有使用var dataform = $('#chatform').serializeArray();,而是使用了var supplierID = $('#supplierID').val();。并将'data':dataform, 更改为'data':{supplierID:supplierID},。但即使我单击列表中的第二个供应商,它也会返回相同的供应商 ID。请参阅上面的图像更新的 Ajax 错误消息,它给了我找到 2 个具有非唯一 ID #supplierID 的元素。我认为这与此有关。

标签: yii2 render ajaxform


【解决方案1】:

正如您所提到的,您在单击两个供应商时会得到相同的supplierID。造成此问题的原因是,在您的 js 代码中,您通过输入的 id 获得 supplierID,即 '#supplierID',并且根据您的 html 代码,两个供应商的输入元素在其 id 属性中具有相同的值,即“supplierID” ,因为每次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();?>

然后从js中按钮的data属性中获取被点击供应商的supplierID。所以你的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);
      }
    });
   });
  });
 ");
?>

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

【讨论】:

  • 我明白了。它现在正在工作。所以你说我基本上可以放弃&lt;input&gt; 元素并将其替换为data-supplierID= 作为button 中的元素之一。你是说不管我用之前用过多少个&lt;input&gt;传递给ajax,我还是会得到和之前一样的错误吗?顺便说一句,感谢您的帮助!
  • 是的,使用data-supplierID= 是一种简单的方法。但是,您也可以使用 &lt;input&gt; 元素来做到这一点,但这会有点复杂
  • 好的。这意味着我仍然可以使用&lt;input&gt; 元素来做到这一点。会记住这一点。感谢您的帮助!
  • 没问题。乐意效劳! :)
猜你喜欢
  • 2012-04-18
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 2020-04-17
  • 2021-06-24
  • 1970-01-01
相关资源
最近更新 更多