2014-05-21 47 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