PHP编程实战15-5

2015-11-09  本文已影响0人  海边拾贝
<!--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元素之后.
上一篇 下一篇

猜你喜欢

热点阅读