我做了一个非常简单的 Ajax 测试代码片段:
<!DOCTYPE html>
<html>
<head>
<script src='main.js'></script>
</head>
<body>
<button id='get-content'>Click</button>
<p></p>
</body>
</html>
main.js
(function(){
window.addEventListener('load', function(){
var xml_request = new XMLHttpRequest();
xml_request.open('GET', '/test.txt', true);
xml_request.addEventListener('readystatechange', change_content);
var button_element = document.getElementById('get-content');
button_element.addEventListener('click', fireup(xml_request));
function fireup(xml_request) {
xml_request.send();
}
function change_content(){
if (xml_request.readyState == 4 && xml_request.status == 200) {
document.getElementsByTagName('p')[0].textContent = xml_request.responseText;
};
};
});
})();
它可以工作,但除了 ajax 请求发送和更改 p 标签,我没有按下按钮,知道吗?