2014-05-21 46 views
0

我想要ajax响应来替换当前文本,但它将追加到顶部。我的HTML页面:用当前文本替换ajax响应

<html> 
<head> 
     <h2>This is a test</h2> 
     <script type="text/javascript" > 

     function ajaxFunction() 
     { 

     var xmlhttp; 
     if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
     } 
     else 
     {// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     xmlhttp.onreadystatechange=function() 
     { 
      if (xmlhttp.readyState==4 && xmlhttp.status==200) 
       { 
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
       } 
      } 

     xmlhttp.open("GET","ajaxinfo.php",true); 
     xmlhttp.send(); 
    } 


     window.onload = function one(){ 
     var a1 = [1,2,3]; 
     for (var i=0;i<a1.length;i++) { 
      var p = document.createElement('p'); 
      p.innerHTML = a1[i]; 
      p.onclick = ajaxFunction; 
      document.body.appendChild(p); 
      } 

     } 

     </script> 
</head> 
<body> 
    <div id="myDiv"> </div> 
</body> 
</html> 

ajaxinfo.php是:

<?php 
    $display=array("Volvo","BMW","Toyota","Maruti","Bugatti"); 

    for($i = 0; $i <sizeof($display);$i++){ 
     echo $display[$i].'<br/>'; 
     } 

?> 

什么我得到是目前Ajax响应是a1阵列上面显示的,但我想Ajax响应,以取代目前阵列显示器。所以,最初的显示是:

//Here goes the heading display 
    1 
    2 
    3 

我最终显示的onclick是:

//Here goes the heading display 
    Volvo 
    BMW 
    Toyota 
    Maruti 
    Bugatti 

不想再在这里显示的前一阵。

回答

0

为什么没有改变:

var p = document.createElement('p'); 

要选择的div?

var p = document.getElementById('myDiv'); 

然后只是删除对appendChild的调用。

for (var i = 0; i < a1.length; i++) { 
    var p = document.getElementById('myDiv'); 
    p.innerHTML += a1[i]; 
    p.onclick = ajaxFunction; 
} 
+0

在这种情况下,只有数组的最后一个元素显示为'3'。 – user2567857

+0

这是因为你正在对同一元素(通过id获取)执行'document.getElementById('myDiv')。innerHTML = a1 [i]',所以每次迭代都会替换前一个元素的内容集。 –

+0

你是否建议一些替代方法? – user2567857