javascript/jquery读取和修改HTTP headers
javascript/jquery读取和修改HTTP headers
jquery修改HTTP headers
jQuery Ajax可以通过headers
或beforeSend
修改request的HTTP headers,例如:
$.ajax({
url: "./test.php",
type: "POST",
headers: {
"Accept" : "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8"
},
/*
beforeSend: function(jqXHR, settings) {
jqXHR.setRequestHeader('Accept', 'text/plain; charset=utf-8');
jqXHR.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');
},
*/
data: {"user" : "min", "pass" : "he"},
error: function(jqXHR, textStatus, errorThrown) {
//....
},
success: function(data, textStatus, jqXHR) {
//....
}
}
注意::W3规定XMLHttpRequest并不能修改全部的HTTP Headers,而仅是一小部分。
jquery获取HTTP headers:
test.html:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
</head>
<body></body>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "./test.php",
type: "POST",
data: {"user" : "min", "pass" : "he"},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert(textStatus + " : " +errorThrown);
} else {
alert(textStatus);
}
},
success: function(data, textStatus, jqXHR) {
alert(jqXHR.getResponseHeader("Server"));
alert(jqXHR.getResponseHeader("Content-Type"));
alert(jqXHR.getResponseHeader("X-Powered-By"));
alert(jqXHR.getResponseHeader("Content-Encoding"));
alert(jqXHR.getAllResponseHeaders());
alert(jqXHR.getResponseHeader("Set-Cookie")); //返回null,不能获取Set-Cookie的值
alert(data + textStatus);
}
});
});
</script>
</html>
test.php:
<?php
if (isset($_COOKIE["time"])) {
$time = $_COOKIE["time"] + 1;
} else {
$time = 1;
}
setcookie("time", $time);
$user = $_REQUEST["user"];
$pass = $_REQUEST["pass"];
print $user.$pass." ".$time;
jQuery通过XMLHttpRequest的getResponseHeader
或getAllResponseHeaders()
可以获取指定的HTTP header field的值,但规定不能获取Set-Cookie
和Set-Cookie2
的值。
参考:
- http://stackoverflow.com/questions/1145588/cannot-properly-set-the-accept-http-header-with-jquery
- http://stackoverflow.com/questions/2444489/getresponseheader-is-not-a-function
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2013-10-28 Html的空格显示
2013-10-28 深入了解setInterval方法