1

我已经尝试了几个小时来让它发挥作用,并且没有动摇。

我想要做的是在单击按钮时发送一个 url,但不刷新页面

按钮的php代码:

    echo '<a href="#" class="approve-button" id="'.$link_url[link_url].'">Send</a>';

jQuery代码:

<script type="text/javascript">

//Attach an onclick handler to each of your buttons that are meant to "approve"
$('approve-button').click(function(){

   //Get the ID of the button that was clicked on
   var id_of_item_to_approve = $(this).attr("id");


   $.ajax({
      url: "votehandler.php", //This is the page where you will handle your SQL insert
      type: "POST",
      data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
      success: function(){
          console.log("AJAX request was successfull");
      },
      error:function(){
          console.log("AJAX request was a failure");
      }   
    });

});

</script>

投票处理程序.php:

<?php

    $data = $_POST['id'];
    mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");

?>

我已经从 votehandler.php 中删除了所有的错误检查,试图得到任何响应,但到目前为止什么都没有。

欢迎任何建议,试图了解 jquery/ajax。

4

1 回答 1

5

您的代码有两个问题:

  • jquery 选择器不工作。正确的是:'a[class="approve-button"]'
  • 代码应该包含在 jqueryready()函数中,以确保在 javascript 代码执行之前已经加载了 DOM(带有链接)。

这是一个工作示例:

$(function() { // wrap inside the jquery ready() function

//Attach an onclick handler to each of your buttons that are meant to "approve"
$('a[class="approve-button"]').click(function(){

   //Get the ID of the button that was clicked on
   var id_of_item_to_approve = $(this).attr("id");


   $.ajax({
      url: "votehandler.php", //This is the page where you will handle your SQL insert
      type: "POST",
      data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
      success: function(){
          console.log("AJAX request was successfull");
      },
      error:function(){
          console.log("AJAX request was a failure");
      }   
    });

});

});
于 2013-05-08T02:38:16.520 回答