2014-04-25 34 views
0

我有一個Ajax請求,它返回一個HTML響應。來自Ajax響應的JQueryUpdate多元素

我想用新內容替換DOM中的現有DIV和相應的ID。

我認爲這種方法是一樣的東西這裏概述:

Update multiple elements with html from jquery ajax call

這是我原來的DOM:

<a onclick="ajaxTest();">Test</a> 
<div id="x"> 
xxx 
</div> 
<div id="y"> 
yyy 
</div> 

這是響應:

<div id="response"> 
    <div id="x" class="room">111</div> 
    <div id="y" class="room">222</div> 
</div> 

這是JS。

function ajaxTest(){ 
    // UPDATE ON SERVER 
    $.post("secure/admin/allocateRoom.do", { 
     bookingId : 3051, 
     roomId : 2291, 
     success : function(data) { 
      var $response = $(data); 
      $response.children().each(function() { 
       alert('in'); 
       $('#' + this.id).html(this.innerHTML); 
      }); 
     } 
    }); 
} 

現在,這適用於以下要求:

$.post("secure/admin/allocateRoom.do", { 
    bookingId : bookingId, 
    roomId : roomId 
}, function(html) { 
    var $response = $(html); 
    $response.children().each(function() { 
     if (this.id) { 
      $('#' + this.id).replaceWith(this); 
     } 
    }); 
}); 
+0

我只是要清除的東西了。你說「這是我的原始DOM」,但那不是DOM。這是你的HTML代碼片段。 DOM要複雜得多,在頁面上並不真正可見,但在頁面上編寫代碼時非常重要。這是一個簡單的方法,但是當你深入研究DOM時,它非常複雜。 – Kehlan

+0

這增加了什麼討論? –

+0

知識。爲什麼你會來堆棧溢出? – Kehlan

回答

0

試試這個;

success : function(data) { 
    var $response = $(data); 
    $response.children().each(function(){ 
     if (this.id) { 
      $('#'+this.id).replaceWith(this); 
     } 
    }); 
} 

DEMO

+0

謝謝,我試過了,至今我可以看到它似乎沒有進入循環。我已經在那裏沒有出現警報。 –

+0

您在問題中發佈的回覆無效HTML。 'id =「response'後缺少一個報價,並且在每個'room' div之後應該是'

',而不是'
'。一旦我解決了這個問題,我的測試循環就會起作用。 – Barmar

+0

是的,只是一個錯字。我已經用原始的HTML,響應和JS更新了這個問題,沒有任何反應!如果我從響應中刪除了外部DIV,那麼我得到一個'無效的XML錯誤',這是有道理的,所以至少會發生一些客戶端的事情。 –