JS通过Ajax获取指定URL响应头字段值

作者:拾光时间:2026-10-29 07:35:23浏览:232

本文介绍如何使用JavaScript的Ajax技术获取指定URL的HTTP响应头信息。通过XMLHttpRequest对象,可以提取如Last-Modified等字段值,适用于需要检查资源元数据的场景。

JS通过Ajax获取指定URL响应头字段值

本文通过具体实例,讲解如何利用JavaScript中的Ajax技术,从指定URL的响应头中提取特定字段值,供读者参考学习。

以下代码演示了如何获取文件ajax_info.txt的响应头信息,重点提取Last-Modified(最后修改时间)属性。


<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
var xmlhttp;
if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
else
 {// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  document.getElementById('p1').innerHTML="Last modified: " + xmlhttp.getResponseHeader('Last-Modified');
  }
 }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<p id="p1">The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('ajax_info.txt')">Get "Last-Modified" information</button>
</body>
</html>

希望本文提供的JavaScript程序设计思路能对读者有所帮助。

作者最新文章