2016-10-19 117 views
0

我正在使用Ajax在單擊按鈕時顯示html頁面。Ajax http請求關閉

我需要的是創建另一個按鈕來關閉ajax html頁面。我嘗試了abort(),但這不是我所需要的,我需要關閉頁面才能中止HTTP請求。

<!DOCTYPE html> 
<html> 

<body> 


    <p id="demo">When you click the button it will load an HTML page</p> 

    <button type="button" onclick="loadDoc()">Open HTML Page</button> 

    <script> 
    function loadDoc() { 
     var xhttp; 
     if (window.XMLHttpRequest) { 
     // code for modern browsers 
     xhttp = new XMLHttpRequest(); 
     } else { 
     // code for IE6, IE5 
     xhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      document.getElementById("demo").innerHTML = this.responseText; 
     } 
     }; 
     xhttp.open("GET", "mypage.html", true); 
     xhttp.send(); 
    } 
    </script> 

</body> 

</html> 
+0

'xhttp.close ()' –

回答

0
<button type="button" 
    onclick="document.querySelector('#demo').style.display='none'">Close HTML Page</button> 

<button type="button" 
    onclick="document.querySelector('#demo').innerHTML==''">Close HTML Page</button> 

這兩者都可以悄悄地使用按鈕

如果你使用首先,你需要添加到裝載的ID被附:

document.querySelector("#demo").innerHTML = this.responseText;  
document.querySelector('#demo').style.display=""; 
+0

你的代碼是完美的,但是爲什麼當我關閉它並再次打開時,一個單詞顯示「undefined」? @mplungjan –

+0

你是否總是打開同一頁面?那麼不要再次做ajax,只需再次顯示頁面 – mplungjan