2014-11-03 139 views
0

我試圖用Ajax更改div的內容,但沒有任何反應......有人能幫我看看我做錯了什麼嗎?AJAX更改HTML內容

據我所見我沒有遺漏任何東西,但按鈕不能連接。我正在運行XAMPP並打開了apache。

索引頁

<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
    <meta name="author" content="Malecia Legodi"> 
    <meta name="description" content="Reload Website"> 
    <script language="JavaScript" src="javascript.js"></script> 
</head> 
<body style="background-color:green"> 
    <div> 
     <nav> 
     <table> 
      <tr> 
       <td> 
        <input type="button" id="home" value="Home"/> 
       </td> 
       <td> 
        <input type="button" id="contact" value="contact" /> 
       </td> 
     </table> 
     </nav> 
     <section> 
      <div id="content" > 
       <h1>Content Review Summary</h1> 
       <p> 
        aaa... 
       </p> 
       <p> 
        bbb... 
       </p> 
      </div> 
     </section> 
     <footer align="center">&copy; Reload Website</footer> 
    </div> 
</body> 
</html> 

接觸頁:

<h1>Content Review Summary</h1> 
<p> 
    ccc... 
</p> 
<p> 
    ddd... 
</p> 

Javascript.js

function initiate(){ 
    content = document.getElementById('content'); 
    var home = document.getElementById('home'); 
    var contact = document.getElementById('contact'); 
    home.addEventListener('click', readHome, false); 
    contact.addEventListener('click', readContact, false); 
} 

function readHome(){ 
    var url = "home.html"; 
    var request = new XMLHttpRequest(); 
    request.addEventListener('load', showContent, false); 
    request.open("GET", url, true); 
    request.send(); 
} 

function readContact(){ 
    var url = "contact.html"; 
    var request = new XMLHttpRequest(); 
    request.addEventListener('load', showContent, false); 
    request.open("GET", url, true); 
    request.send(); 
} 

//function showContent() to add data into your 
function showContent(e){ 
    //add data to secContent 
    content.innerHTML = e.target.responseText; 
} 

//use the listener to load your initiate() function 
window.addEventListener('load', initiate, false); 
+0

您是否收到任何錯誤? – ankur 2014-11-03 06:31:29

+0

你在哪裏聲明瞭內容變量? – Amy 2014-11-03 06:33:38

+0

@ankur,不,我沒有得到任何錯誤,頁面根本不會改變。 – 2014-11-03 06:37:53

回答

0

變化DIV ID contentsecContent"

也改變:

content = document.getElementById('content'); 

content = document.getElementById('secContent'); 

除了:

content.innerHTML = e.target.responseText; 

secContent.innerHTML = e.target.responseText; 

你的JavaScript的過去的代碼塊是完全一樣的,以我在大學時獲得了一個例子(雖然有問題的例子只是讀取一個.txt文件而不是幾個htmls,但它有相同的問題)。我設法通過上面提到的方法來實現它。希望它也能幫助你。