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.)

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题