如何在添加和删除Ajax文本之间切换

时间:2018-10-08 16:03:03

标签: javascript ajax

我是一名编程专业的学生,​​我已经完成了该程序的编写,该程序在服务器中添加了rain.text,内容为“西班牙的雨主要停留在平原上”。但是我希望程序在用户再次单击按钮时删除雨文本,然后在用户再次单击按钮时再次添加rain.txt。请问如何解决这个问题?

<html>
<head>

<style>

#hidereveal
{
margin:auto;
width:90%;
height:auto;
border: 1px black solid;
text-align:center;
}

p
{
text-align:center;
}
</style>
</head>
<body>

<div id="hidereveal">

<p>this is a test, when you click the button and ajax will add in more data 
from the server<button type="button" onclick="loadDoc()">Click to read 
more</button></p>


</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  document.getElementById("hidereveal").innerHTML += this.responseText;
}
};
xhttp.open("GET", "rain.txt", true);
xhttp.send();
 }
</script>

</body>




</html>

2 个答案:

答案 0 :(得分:0)

我将替换此代码

document.getElementById("hidereveal").innerHTML += this.responseText;

使用此代码

let elem = document.getElementById("hidereveal")
elem.innerHTML !== '' ? elem.innerHTML = '' : elem.innerHTML += elem.innerHTML

<html>
<head>

<style>

#hidereveal
{
margin:auto;
width:90%;
height:auto;
border: 1px black solid;
text-align:center;
}

p
{
text-align:center;
}
</style>
</head>
<body>

<div id="hidereveal">

<p>this is a test, when you click the button and ajax will add in more data 
from the server<button type="button" onclick="loadDoc()">Click to read 
more</button></p>


</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let elem = document.getElementById("hidereveal");
elem.innerHTML !== '' ? elem.innerHTML = '' : elem.innerHTML += elem.innerHTML
}
};
xhttp.open("GET", "rain.txt", true);
xhttp.send();
 }
</script>

</body>




</html>

答案 1 :(得分:0)

只是出于兴趣,这是经过反复试验后得出的版本!尤其是使用Ajax或多或少显示文本而无需重新加载页面的函数,效果很好。

<html>
<head>

<style>

#hidereveal
{
margin:auto;
width:90%;
height:auto;
border: 1px black solid;
text-align:center;
}

p
{
text-align:center;
}
</style>
</head>
<body>

<div id="hidereveal">

<p>This is a test, when you click the button, ajax will add in more data 
from the server. <button type="button" onclick="loadDoc()">Read more or less! 
</button></p>
<div id="xml"></div>

</div>

<script>



function loadDoc() {
if(document.getElementById("xml").innerHTML == ''){

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("xml").innerHTML += this.responseText;
}
};
xhttp.open("GET", "rain.xml", true);
xhttp.send();
}
else 
{
document.getElementById("xml").innerHTML="";  
}



}

</script>


</body>