Ajax 读取响应首部

如果验证服务器是否正常运行,只想读取服务器发出的响应首部,可以使用HEAD请求。通过HEAD请求可以获得以下内容:

  • Content-Type(内容类型)
  • Content-Length(内容长度)
  • Last-Modified(最后一次修改的时间)

示例如下:

 

readingResponseHeaders.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	
<html>
<head>
<title>Reading Response Headers</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 doHeadRequest(request, url) {
	requestType = request;
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.open("HEAD", 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:doHeadRequest('allResponseHeaders','./xml/readingResponseHeaders.xml')">Read All Response Headers</a>
<br />
<a href="javaScript:doHeadRequest('lastModified','./xml/readingResponseHeaders.xml')">Get Last Modified Date</a>
<br />
<a href="javaScript:doHeadRequest('isResourceAvailable','./xml/readingResponseHeaders.xml')">Read Available Resource</a>
<br />
<a href="javaScript:doHeadRequest('isResourceAvailable','./xml/not-available.xml')">Read Unavailable Resource</a>

</body>

</html>	

	

 

你可能感兴趣的:(JavaScript,html,xml,Ajax,Microsoft)