douchen5971 2019-01-04 13:48
浏览 67
已采纳

jquery - ajax - 逐个更新列的问题

i want to update each columns acording by id, when i click on an image, without refresh all the page. my codes just update last ids column when i click each on images.
index.php:

$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid=1");
        while($rw=mysqli_fetch_assoc($rzp)){$id=$rw['id'];
            echo $id;?><img id="up" src="pc3/up.png" alt=""><br>
 <?php }?>
 <script>
 $(document).ready(function() {
   var id = <?php echo $id;?>;

  $(document).on("click","#up",function() {
    $.ajax({
        method: "POST",
       url: "y2.php",
        data: {id: id},
                async :false
      }).done(function(msg2) {
        alert(msg2);
      });
  });
  });
 </script> 

y2.php:

$id=$_POST['id'];
    mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");

thanks

  • 写回答

1条回答 默认 最新

  • duanjia4220 2019-01-04 13:58
    关注

    There are a couple things immediately wrong here:

    • You are re-using id values in your HTML, which is invalid.
    • Your var id = ... JavaScript code always has the last value from your data, and you're explicitly using that every time instead of any value from your HTML element.

    Let's simplify. First, echo your HTML elements to include (1) a class to use for triggering the click handler and (2) the ID that the click handler needs:

    <?php
    while($rw=mysqli_fetch_assoc($rzp)){
        $id=$rw['id'];
        echo $id;
    ?>
        <img class="up" src="pc3/up.png" alt="" data-id="<?php echo $id; ?>"><br>
    <?php } ?>
    

    (Note: There's probably a much cleaner way to do that. I'm attempting to maintain the coding style you currently have, but you should definitely look into cleaner approaches of writing code overall.)

    Now you have a bunch of images with (1) a class called "up" and (2) a data- attribute with the ID you need upon clicking. Your click handler can now use that information:

    $(document).on("click", ".up", function() { // use the class as the selector
      var id = $(this).data('id'); // get the data-id value from this specific element
      $.ajax({
        method: "POST",
        url: "y2.php",
        data: {id: id}
      }).done(function(msg2) {
        alert(msg2);
      });
    });
    

    (Note: I also removed async: false because one should never use async: false. If there's some reason you think you need to use it, that's a different problem entirely and one that should be addressed as well.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区