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.

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

  $(document).on("click","#up",function() {
        method: "POST",
       url: "y2.php",
        data: {id: id},
                async :false
      }).done(function(msg2) {


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


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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:

        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
        method: "POST",
        url: "y2.php",
        data: {id: id}
      }).done(function(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.)

    解决 无用
    打赏 举报

相关推荐 更多相似问题