2012-02-05 80 views
2

我有這個ajax代碼,其中顯示更多的細節1 Div ..我的問題是如何在兩個或三個div顯示ajax?Ajax多個div

function GetDetails(id) 
    { 
     $(document).ready(one); 
     function one() 
     { 
     if(window.XMLHttpRequest){ 

     xmlhttp = new XMLHttpRequest(); 
     }else { 
     xmlhttp = new ActiveXObject('Micrososft.XMLHTTP'); 
     } 

     xmlhttp.onreadystatechange = function() { 
     if(xmlhttp.readyState ==4 && xmlhttp.status == 200) { 
     document.getElementById('tv'+id).innerHTML = xmlhttp.responseText; 
     } 
     } 
     xmlhttp.open('GET', 'ajax.php?c='+id, true); 
     xmlhttp.send(); 
     var thebutton = '#button'+id; 
     $(thebutton).hide(); 
     } 
    } 
+1

你是什麼意思?你想打破更多div的結果還是你想獲得更多的div值? – axiomer 2012-02-05 09:34:55

+1

如果您使用的是jQuery,那麼您爲什麼不使用['。.load()'](http://api.jquery.com/load/)? – DaveRandom 2012-02-05 09:37:51

+0

我有兩種數據我想在不同的div中顯示它們,而不是一個。 – 2012-02-05 09:39:16

回答

0

如果你有什麼事情,肯定不會在您的輸出,獨立要分開在PHP代碼,那麼JS的東西,使用xmlhttp.responseText.split或PHPJS.org的[explode()][1]如果沒有這樣的事情,那麼你也許應該確保會有。不知何故,例如,在PHP中使用str_replace()

或者,或者,如果您有足夠的帶寬,請發送多個請求。

0

也許最簡單,最快,也是「最佳實踐」的方法如下:

假設你正在使用jQuery和你有多個div,說兩句,看起來像這樣

<div id="tv1More"> 
    We need to add this div somewhere... 
</div> 
<div id="tv2More"> 
    and this one somewhere else (with 1 ajax call!) 
</div> 

首先,把另一格的任何地方你的頁面,默認是隱藏在

<div id="receiver" style="display:none;"> 
</div> 

然後改變你的線

document.getElementById('tv'+id).innerHTML = xmlhttp.responseText; 

到一個更新兩個div如下:

//Put the retrieved HTML into the DOM 
$("#receiver").html(xmlhttp.responseText); 
$(document.getElementById('tv'+1)) //Select the div that needs to be updated 
    .html($("#tv1More").html()); //and update the first div 
$(document.getElementById('tv'+2)) //and also 
    .html($("#tv1More").html()); //the second div 

我沒有實際測試上面的代碼,所以有可能是拼寫錯誤。

通常使用單個ajax調用會更好,因爲它會顯着縮短頁面加載的時間。