2010-10-30 49 views
2

我有一個簡單的AJAX功能對象的ID發送給PHP頁面AJAX POST不工作,想不通爲什麼

我的功能看起來是這樣的:

$(function(){  
    $("a.vote").click(function(){ 
     //get the id 
     the_id = $(this).attr('id'); 
     alert(the_id); 

     //ajax post 
     $.ajax({ 
      type: "POST", 
      data: "?id="+the_id, 
      url: "vote.php", 
      success: function(msg) 
      { 
       $("span#message"+the_id).html(msg); 
      } 
     }); 
    }); 
}); 

我的投票。 PHP是這樣的:

session_start(); 
if(isset($_SESSION['user'])) { 
    // db setup removed 

    // insert vote into db 
    $q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id']; 
mysql_query($q);  
echo "You sent " . $_POST['id']; 
} 

當我執行我的AJAX功能,看來vote.php永遠不會運行

我知道我的AJAX函數被正確調用,因爲alert(the_id);正在彈出正確的ID。

我知道我的vote.php工作正常,因爲我可以用一個名爲「ID」文本框中運行HTML方法=「郵報」,它會正確地更新數據庫。

任何人都可以看到有什麼問題嗎?

謝謝

回答

4

你試圖把你的變量在URL中,而不是作爲POST變量。應該是這樣的:

$(function(){  
    $("a.vote").click(function(){ 
     //get the id 
     var the_id = $(this).attr('id'); 
     alert(the_id); 

     //ajax post 
     $.ajax({ 
      type: "POST", 
      data: {id:the_id}, 
      url: "vote.php", 
      success: function(msg) 
      { 
       $("span#message"+the_id).html(msg); 
      } 
     }); 
    }); 
}); 

您的數據應該包含在一個對象中,而不是字符串URL。查看jquery API頁面上的示例以瞭解更多信息!

2

我在你的代碼中看到的首要大事,不右看看是data: "?id="+the_id,?是不必要的,對於發佈請求並不合邏輯。請改爲:

data: { 
    id: the_id 
} 

這可以讓jQuery爲您執行URL編碼。

另外一點,你做$(this).attr(id)。這是非常低效的。做this.id而是整整的百倍更快at least 20 times quicker同樣的效果。