2012-02-05 78 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调用会更好,因为它会显着缩短页面加载的时间。