用当前文本替换ajax响应

Replace ajax response with current text

本文关键字:ajax 响应 文本替换      更新时间:2023-09-26

我希望ajax响应取代当前文本,但它是附加在顶部。我的html页面是:

<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

不希望在这里再显示之前的数组

为什么不更改:

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;
}