2012-01-11 51 views
1

我有點擊鏈接時運行的一些jquery(下圖)。這允許數據被髮送到mysql數據庫,然後更新某個<p>的值。但是,這不起作用。我添加了一個alert(response),我得到了正確的結果,但<p>沒有更改,這可能意味着我使用了錯誤的選擇器。jquery post不改變響應值

JQUERY:

$('.upVote').click(function(e){ 

    e.preventDefault(); 

     answer_id = $(this).siblings('.record_id').attr('value'); 

     $.post('../answerrating.php' , {answer_id: answer_id} , function(response){ 

      $(this).prev('.ratingBox').val(response); 
     }); 

}); 

HTML:

<p class='ratingBox'> $answerrating[$f]</p> 
        <a href='#' class='upVote'>Upvote</a> <a href='#' class='downVote'>Downvote</a> 
        <input type='hidden' name='record_id' value='$answerid[$f]' class='record_id' /> 
+0

什麼是響應? html ???? – 2012-01-11 03:34:33

+0

@ dku.rajkumar響應是一個數字,從PHP回聲像'25'。我想這個數字是在.ratingBox – kirby 2012-01-11 03:37:50

+0

可能重複[如何訪問$(this)裏面的ajax成功回調函數](http://stackoverflow.com/questions/2643798/how-to-access-the-這在裏面ajax成功回調函數) – 2012-01-11 03:38:46

回答

2

試試這個。

$('.upVote').click(function(e){  
    e.preventDefault();  
    var target_elem = $(this).prev('.ratingBox'); 
     answer_id = $(this).siblings('.record_id').attr('value');  
     $.post('../answerrating.php' , {answer_id: answer_id} , function(response){  
      target_elem.text(response); 
     });  
}); 
1

this將不參考單擊了AJAX的回調裏面的元素。嘗試存儲事件處理程序的上下文,並將其用於回調函數中。

$('.upVote').click(function(e){ 
    var self = this; 

    e.preventDefault(); 

     var answer_id = $(this).siblings('.record_id').attr('value'); 

     $.post('../answerrating.php' , {answer_id: answer_id} , function(response){ 

      $(self).prev('.ratingBox').html(response); 
     }); 

}); 
+0

謝謝,但它沒有工作 – kirby 2012-01-11 03:38:30

+0

@ user802370:什麼反應是什麼樣的?這是你期望的嗎? – 2012-01-11 03:40:16

+0

是的,在我的問題中,我說我得到了預期的結果 – kirby 2012-01-11 03:43:44

0

的錯誤可能是因爲特殊變量this.post()成功回調裏面的值幾乎可以肯定:

另外,你應該修改非input元素的內容時使用.text().html()而不是單擊事件處理程序正在響應的DOM元素。

要解決這個問題,請在點擊回調中爲this的值設置一個變量,並在成功回調中引用它。一般來說,這是一個很好的做法,無論您何時不能100%確定this的價值是什麼,因爲它因上下文而異。

$('.upVote').click(function(e){ 
    var button = this; 
    e.preventDefault();  
    answer_id = $(this).siblings('.record_id').attr('value'); 

    $.post('../answerrating.php' , {answer_id: answer_id} , function(response){ 
     $(button).prev('.ratingBox').val(response); 
    }); 
}); 
+0

將answer_id行更改爲'var answer_id = $(button)...'也可能有幫助,確保使用'var'關鍵字來避免創建全局變量。 – GregL 2012-01-11 03:39:51