2010-07-01 19 views
0

在下面的代碼中,我希望定期更新表格中的每一行。有了這段代碼,我可以調用一個url來傳遞每個div的id作爲參數,並從我的服務器獲取正確的替換html行。不幸的是,一旦我回到了HTML,我無法弄清楚如何正確地替換每個div的內容。使用jquery,你如何用url返回的比賽更新一行HTML表格?

你會如何更新這個jQuery代碼來更新每個div基於從服務器返回的HTML?

<table class="problems" cellspacing="0" width="900"> 
     <tr style="color:#00ce1d;font-weight:bold;text-align:left"> 
     <td>One</td><td>Two</td> 
     </tr> 

     <tr> 
     <div id='1' class='playerRow'> 
      <td> One</td> 
      <td> Two</td> 
     </div> 
     </tr> 

     <tr> 
     <div id='2' class='playerRow'> 
      <td> One</td> 
      <td> Two</td> 
     </div> 
     </tr> 

    </table> 


function updateRows() { 
     var getDivs = 0; 

     //iterate div with class playerRow 
     $("div.playerRow").each(function() { 
      alert('div id--'+this.id); 
      var theDiv = $(this) 

      // send ajax requrest to url encoded as div.id 
      $.get('/myServerUrl?id='+this.id, function(data) { 
       //The right url response comes back 
       alert('div id--'+this.url+'--ajax response--'+data); 

       //###### Problem area ########## 
       //Can't figure out how to view the current Div contents or update them. 
       //alert('current contents ='+theDiv.html()); 
       //theDiv.replaceWith(data); 
       //alert('current contents ='+theDiv.html());    
      }); 
      }); 
    } 
    updateRows(); //The first time 

回答

2

首先您的標記是錯誤

<tr> 
    <div id='1' class='playerRow'> 
     <td> One</td> 
     <td> Two</td> 
    </div> 
    </tr> 

的TD不以DIV,但在TR屬於!

你應該先解決。這應該工作:

<tr id='1' class='playerRow'> 
     <td> One</td> 
     <td> Two</td> 
    </tr> 

也許jQuery的.load是你所需要的:

描述:將數據從服務器返回的HTML 放入匹配元素。

load(url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ]) 

網址的含有URL字符串到的請求被髮送。

數據與請求一起發送到服務器的映射或字符串。

complete(responseText,textStatus,XMLHttpRequest)請求完成時執行的回調函數。

樣品:

$('#result').load('ajax/test.html'); 

所以,你的代碼將

$(".playerRow").each(function() { 
       $(this).load('/myServerUrl?id='+this.id) 
    }) 
+0

我很謙虛。正是我需要的。謝謝。 – Chris 2010-07-01 10:05:51

0

我不知道什麼是/myServerUrl?id='+this.id

響應,但也許你應該試着

$.get('/myServerUrl?id='+this.id, function(data) { 
     $('#'+this.url).html(data); 
}); 
相關問題