2012-07-11 69 views
0

我想使用jQuery ajax請求的響應來設置div的innerHTML與一個特定的ID。這是我使用的代碼:如何使用ajax jQuery響應中傳回的數據?

$(".show_comments").click(function(){ 


var articleName = $(this).closest("article").find(".articlename").attr('id') 

$.ajax({ 
url: "commentView.php", 
data: { 'articleName': articleName }, 
cache: false, 
dataType: "html", // so that it will auto parse it as html 
success: function(response){ 
$(this).closest("article").find(".comments").html(response); 
} 
}); 

但它似乎並沒有在所有做任何事情,我已經試過周圍的Googling,但一切都可以找我說要做到這一點我做的方式...我已經在Firebug進行了測試,並且ajax請求也給了我我想要的確切響應...但是我只是無法訪問此設置div的innerHTML來響應!

回答

2

在您的ajax成功處理程序中有另一個範圍和this指向不是你想象的。因此,改變你的代碼:

var articleName = $(this).closest("article").find(".articlename").attr('id'), 
    that = this; 

$.ajax({ 
    url: "commentView.php", 
    data: { 'articleName': articleName }, 
    cache: false, 
    dataType: "html", // so that it will auto parse it as html 
    success: function(response){ 
     $(that).closest("article").find(".comments").html(response); 
    } 
}); 

我改變什麼:我補充that變量,指向this實例,並在成功處理程序使用它來代替。

你將如何自己調試它:如果你試圖輸出console.log(this)console.log($(this).closest("article").find(".comments"));你會發現它返回一個錯誤的對象(第一種情況),而第二種情況則沒有。

+0

將其更改爲'that'後,出現錯誤:未定義... – simonthumper 2012-07-11 23:33:46

+0

Ohhhh!我的壞錯過了XD – simonthumper 2012-07-11 23:34:07

+0

輝煌的工作完美! :) – simonthumper 2012-07-11 23:36:07