Ajax:读取响应首部

   有时,只是想“ping”一下服务器,验证服务器是否正常运行。此时,只需要读取服务器发出的响应首部,而忽略内容。通过读取响应首部,可以得出content-Type(内容类型)、Content-Length(内容长度)。甚至LastModified(最后一次修改)的日期。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        var xmlHttp;
        var requestType = "";
        function createXMLHttpRequest() {
            if (window.ActiveXObject) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTp");
            }
            else if (window.XMLHttpRequest) {
                xmlHttp = new XMLHttpRequest();
            }
        }


        function doRequest(request, url) {
            createXMLHttpRequest();
            requestType = request;
            xmlHttp.onreadystatechange = handleStateChange;
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null);
        }
        function handleStateChange() {
            if (xmlHttp.readyState == 4) {

                if (requestType == "allResponseHeaders") {
                    getAllResponseHeaders();
                }
                else if (requestType == "lastModified") {

                    getLastModified();
                }
                else if (requestType == "isResourceAvailable") {
                    getIsResourceAvailable();
                }

            }
        }
        function getAllResponseHeaders() {

            alert(xmlHttp.getAllResponseHeaders());
        }
        function getLastModified() {
            alert("Last Modified:" + xmlHttp.getResponseHeader("Last-Modified"));
        }

        function getIsResourceAvailable() {
            if (xmlHttp.status == 200) {
                alert("Successful response");
            }
            else if (xmlHttp.status == 404) {
                alert("Resource is unavailable");
            }
            else {
                alert("Unexpected response status:" + xmlHttp.status);
            }
        }
    </script>
</head>
<body>
    <h1>
        Reading Response Headers</h1>
    <a href="javascript:doRequest('allResponseHeaders','readingResponseHeaders.xml');">Read
        All Resoponse Headers</a><br />
    <a href="javascript:doRequest('lastModified','readingResponseHeaders.xml');">Get Last
        Modified Date</a><br />
    <a href="javascript:doRequest('isResourceAvailable','readingResponseHeaders.xml');">
        Read Available Resource </a>
    <br />
    <a href="javascript:doRequest('isResourceAvailable','no-available.xml');">Read UnAvailable
        Resource </a>
    <br />
</body>
</html>

readingResponseHeaders.xml文件内容为:

<?xml version="1.0" encoding="utf-8" ?>
<readingResponseHeaders>

</readingResponseHeaders>

执行效果如下:

挨个点击出现效果:

posted on 2012-10-08 19:39  lufangtao  阅读(223)  评论(0编辑  收藏  举报

导航