使用AJAX将数据插入数据库时​​出现问题

I am in problem with this code snippet, its not working :

.
.
.
<a href="#" id="$_GET['id1']" onclick="addToDb(<?php echo $_GET['id2'];?>)">Its a link</a>
.
.
.

The "addToDb()" function:

<script>
     function addToDb(e)
     {alert(e);
         $.post("add_to_db.php",
         {
             id2:e,
             id1:this.attr("id")
         },
         function(data,status){
            alert("Data: "+data+"
Status: "+status);
         });
     }
 </script>

This function works, because "alert(e)" gives the value of the "id2". Probably something is wrong with id1:this.attr("id"), I tried "alert(this.attr("id"))", didn't work.

The "add_to_db.php" page is :

<?php
  $connection=mysql_connect("localhost","root","") OR die('Could not connect: '.mysql_error());
  mysql_select_db("db_user",$connection);
?>
<?php
$id2=htmlspecialchars(trim($_POST['id2']));
$id1=htmlspecialchars(trim($_POST['id1']));
?>

<?php
$duplicacy_check="select * from tbl_name where id2='$id2' && id1='$id1' LIMIT 1";
$duplicacy_check_result=mysql_query($duplicacy_check) or die(mysql_error());
    if($duplicacy_check_result)
  {
?>
      <script>
          alert("Its already added !");
      </script>


<?php
      exit();
  }
else
  {
      $query="INSERT INTO tbl_name(id2,id1) VALUES('$id2','$id1')";
      mysql_query($query) or die(mysql_error());
?>
      <script>
          alert("Added to the db");
      </script>
<?php
  }
?>

Don't be confused with "id1", "id2", "tbl_name", etc., or the order of "id1" and "id2", that is alright, I know.

Please help me, I am in trouble with this simple thing last 2 days.

Please try following:

<a href="#" id="$_GET['id1']" onclick="addToDb(<?php echo $_GET['id1'];?>, <?php echo $_GET['id2'];?>)">Its a link</a>

and

<script>
     function addToDb(a, e)
     {
         $.post("add_to_db.php",
         {
             id2:e,
             id1:a
         },
         function(data,status){
            alert("Data: "+data+"
Status: "+status);
         });
     }
 </script>

I believe the error is as you say: this.attr("id") Example: http://jsfiddle.net/fAHye/

change your function to this:

<script>
     function addToDb(elm, e)
     {alert(e);
         $.post("add_to_db.php",
         {
             id2:e,
             id1:elm.getAttribute("id")
         },
         function(data,status){
            alert("Data: "+data+"
Status: "+status);
         });
     }
 </script>

and HTML to

<a href="#" id="<?php echo $_GET['id1']; ?>" onclick="addToDb(this,<?php echo $_GET['id2'];?>)">Its a link</a>

Note: <?php echo $_GET['id1']; ?>

Also the fact that the trigger is in a link might give you some trouble as the page will change, try using another tag or remove the default link http://api.jquery.com/event.preventDefault