2011-12-20 15 views
2

選択したhtml行のコンテンツをサーバーデータで更新しようとしています。 選択したhtml行を静的データで更新することも、すべてのhtml行をサーバーデータで更新することもできます。 選択したhtml行をサーバーデータで更新できません。

$('td.table_with_server_update a').click(function(){  
    var var1=$(this).data('variable1'); 

これは、静的なコンテンツを持つ選択されたHTMLの行を更新、これは私が何をしたいのかですが、サーバーのデータと。

$(this).parent().prev().html('static content'); 

    $.post("server_side_process.php",{varone: var1}, function(data){    

HTMLテーブル内のすべての要素を選択すると、サーバーのデータを更新し、これは次の私は私が欲しいと思うものをサーバのデータを持つ行が

$('td.table_with_server_update').prev().html(data); //updates all html rows  

これは、「クリック」だけ更新したい、働きこれを表現する方法はわかりません。私は私の問題は、コールバック関数$.post()コールバック内部

$(this).parent().prev().html(data); // no error in firebug, but doesn't rewrite html 

    });   
    });            
}); 

...

<table border="1"> 
    <tr> 
    <td>rewrite this data </td><td class="table_with_server_update"><a href="javascript:void(0)" data-variable1='1'>Update this row</a> </td> 
    </tr> 
    <tr> 
    <td>rewrite this data</td><td class="table_with_server_update"><a href="javascript:void(0)" data-variable1='2'> Update this row</a></td> 
    </tr>  

答えて

2

this内部$(この)だと思う は、アンカー要素にjQueryのXHRオブジェクトを参照していません。アンカー要素のコンテキスト内のthisを変数に保存し、$.post()コールバック内でその変数にアクセスする必要があります。

これを試してみてください:

$('td.table_with_server_update a').click(function() { 
    // save "this" into $this variable directly as jQuery object 
    var $this = $(this); 
    var var1 = $this.data('variable1'); 

    $this.parent().prev().html('static content'); 

    $.post("server_side_process.php",{varone: var1}, function(data) { 
     $('td.table_with_server_update').prev().html(data); //updates all rows 
     // use saved "$this" = anchor instead of "this" = jQuery XHR object 
     $this.parent().prev().html(data); 
    }); 
}); 
0

その他のソリューションは、うまく動作しますが、代替は$.post$.ajaxの長い形式を使用することであり、contextオプション設定:

$('td.table_with_server_update a').click(function(){  
    var var1 = $(this).data('variable1'); 

    $.ajax({ 
     type: 'POST', 
     url: "server_side_process.php", 
     data: { varone: var1 }, 
     context: this, /* Set the context of ajax-related callbacks */ 
     success: function (data) { 
      /* "this" is now correct */ 
      $(this).parent().prev().html(data); 
     } 
    }); 
}); 

を例:http://jsfiddle.net/vUaUV/

関連する問題