I made a very simple Ajax test code snippet:
<!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;
};
};
});
})();
it works, but except, the ajax request send and change the p tag, without I hit the button,
any idea?
In this line, you call
fireup(xml_request), and assign whatever it returns (nothing) as a listener for theclickevent. You probably want something like this:Since
xml_requestis in scope for thefireupfunction, you don’t need to pass it as a parameter.