AJAX更改HTML内容

AJAX Change HTML Content

本文关键字:内容 HTML 更改 AJAX      更新时间:2023-09-26

我正试图用Ajax更改div的内容,但什么也没发生。。。有人能帮我看看我做错了什么吗?

据我所见,我没有遗漏任何东西,但按钮没有接通。我正在运行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);

将div id content更改为secContent"

同时更改:

content = document.getElementById('content');

content = document.getElementById('secContent');

以及:

content.innerHTML = e.target.responseText;

secContent.innerHTML = e.target.responseText;

你的javascript的最后几块代码与我在大学时的一个例子完全相似(尽管这个例子只读取了一个.txt文件,而不是几个html,但它也有同样的问题)。我设法通过上面提到的方法使它发挥作用。希望它也能帮助你。