Javascript 用当前文本替换ajax响应
我希望ajax响应替换当前文本,但它会附加在顶部。我的html页面是:Javascript 用当前文本替换ajax响应,javascript,php,ajax,Javascript,Php,Ajax,我希望ajax响应替换当前文本,但它会附加在顶部。我的html页面是: <html> <head> <h2>This is a test</h2> <script type="text/javascript" > function ajaxFunction() { var xmlhttp; if (window.XMLHttpRequest)
<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>
我目前得到的是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;
}
for(变量i=0;i
在这种情况下,只显示数组的最后一个元素,即3
。这是因为您正在对同一个元素(get by id)执行document.getElementById('myDiv')。innerHTML=a1[i]
,因此每次迭代都会替换上一次迭代的内容集。您是否建议其他方法?
for (var i = 0; i < a1.length; i++) {
var p = document.getElementById('myDiv');
p.innerHTML += a1[i];
p.onclick = ajaxFunction;
}