Ajax / jquery如何从按钮单击发送数据而不刷新页面

时间:2013-05-08 02:29:11

标签: php jquery mysql ajax

我已经花了好几个小时让这个工作起来并没有动摇一个预算。

我尝试做的是点击按钮时发送网址,但不刷新网页

按钮的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>

votehandler.php:

<?php

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

?>

我已经从votehandler.php中删除了所有错误检查,试图得到任何回复,但到目前为止还没有。

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

1 个答案:

答案 0 :(得分:5)

您的代码有两个问题:

  • jquery选择器无法正常工作。正确的是:'a[class="approve-button"]'
  • 代码应该包含在jquery ready()函数中,以确保在执行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");
      }   
    });

});

});