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 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!