PHP编程实战15-5

<!--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元素之后.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容