欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ajax head方式读取头部响应

程序员文章站 2022-07-09 09:01:48
...
readingResponseHeaders.html中的代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</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){
			createXMLHttpRequest();
			requestType = request;
			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 == "isResourceAvaiable") {
					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("unexcepted response status : " + xmlHttp.status);
			}
		}
		
		function parseResults(){
		
			var responseDiv = document.getElementById("serverResponse");
			if (responseDiv.hasChildNodes()){
				responseDiv.removeChild(responseDiv.childNodes[0]);
			}
			
			var responseText = document.createTextNode(xmlHttp.responseText);
			responseDiv.appendChild(responseText);
		}
	</script>
</head>
<body>
	<h1>reading response headers  </h1><br><br>
	<a href="javascript:doHeadRequest('allResponseHeaders','readingResponseHeaders.xml');">getAllResponseHeaders</a><br/><br/>	
	<a href="javascript:doHeadRequest('lastModified','readingResponseHeaders.xml');">lastModified</a><br/><br/>	
	<a href="javascript:doHeadRequest('isResourceAvaiable','readingResponseHeaders.xml');">getIsResourceAvailable</a><br/><br/>	
	<a href="javascript:doHeadRequest('isResourceAvaiable','notAvailableResource.xml');">getIsResourceAvailable</a><br/><br/>	
</body>
</html>



做为客户端请求文件:readingResponseHeaders.xml,只是为了表明这个文件在服务端存在,内容可以为空。

有一点很奇怪,xmlHttp.open("HEAD",url,true); 我把"HEAD"改为"head",alert弹出的内容会有点不一致。