weixin_33744854 2017-12-22 18:45 采纳率: 0%
浏览 205

Ajax在while循环中

I'm building push notifications for my messaging system and have a weird bug.

I'm using an ajax to get recent messages. In my PHP script I have a while loop where I go through my results. So each <li> is a 'recent message'.

In my mind it would be simple. I put an ajax function in the <li> and as it iterates through the while loop it will send the values received from the iteration. Below is my PHP script.

$output .= "
  <li>
    <img src='$profilephoto' class='rm_pp' alt=''>
      <div class='imNotification'>
       <script>
         function getIMNotification() {
           $.ajax({
             url: 'getIMNotification.php',
             method: 'POST',
             data:{user2:'$id'},
             success:function(data) {
               $('.imNotification').html(data);
             }
           });
         }

         getIMNotification();
       </script>
     </div>
  </li>
";

For example, in my getIMNotification.php if i just echo the user2 value sent from my AJAX, it will echo the same value for each result. But, since it's in the while loop, shouldn't it receive new values each iteration?

Is it because of the function being called? The one value being echoed is the last id in the loop. Any logic as to why it's doing that?

  • 写回答

1条回答 默认 最新

  • 乱世@小熊 2017-12-22 18:59
    关注

    You shouldn't redefine the function in the loop. You should define the function once, and have it take the ID as a parameter. Then you can call it separately for each LI.

    You also need to put the result in the specific DIV for that message. .imNotification selects all the DIVs with that class. You can use $id in the ID of the DIV to target each one.

    The function doesn't need to come from AJAX, you can just put this in the original HTML:

    function getIMNotification(id, target) {
      $.ajax({
        url: 'getIMNotification.php',
        method: 'POST',
        data: {
          user2: id
        },
        success: function(data) {
          $('#' + target).html(data);
        }
      });
    }
    

    Then the PHP would be:

    $output .= "
      <li>
        <img src='$profilephoto' class='rm_pp' alt=''>
          <div class='imNotification' id='imNotification-$id'>
           <script>
             getIMNotification('$id', 'imNotification-$id');
           </script>
         </div>
      </li>
    ";
    
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程