Ajax的关键在于XMLHttpRequest对象,理解这个对象的例子如下:
<!DOCTYPE HTML>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<div>
<button>Apple</button>
<button>Samsung</button>
<button>IBM</button>
</div>
<div id="target">
Press a button
</div>
<script>
var buttons = document.getElementsByTagName("button");
for(var i = 0; i < buttons.length; i++){
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("GET",e.target.innerHTML + ".html");
httpRequest.send();
}
function handleResponse(e){
if(e.target.readyState == XMLHttpRequest.DONE &&
e.target.status == 200){
document.getElementById("target").innerHTML
= e.target.responseText;
}
}
</script>
</body>
</html>
原文链接:https://www.f2er.com/ajax/161876.html