<!--PHP编程实战-->
<!--JSON & Ajax -->
<!--15-5-->
<!--使用XMLHttpRequest修改页面元素-->
<html>
<head></head>
<body>
<p>Original content</p>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
// 指定请求的属性 URL为当前页
xhr.open("GET", window.location.pathname, true);
// window.location.pathname==untitled/a.php
// 定义回调函数
xhr.onreadystatechange = function () {
//console.log(xhr.readyState);
if (xhr.readyState == 4) {
var message = "";
//console.log(xhr.status);
if (xhr.status = 200) {
message = "Ajax loaded content";
}
else {
message = "An error has occured making the request";
}
document.getElementsByTagName("p")[0].innerHTML = message;
}
}
// 发送实际的请求
xhr.send(null);
</script>
</body>
</html>
- open()中使用的URL是当前页window.location.pathname
能够看到从其初始值"Original content"到"Ajax loaded content"的改变
- xhr.send(null)发送请求不包含数据
- 因为需要加载整棵DOM树,JavaScript置于HTML元素之后.