jQuery、YUI 等庫在發送 Ajax 請求時,默認會附帶一個名為 X-Requested-With 的請求頭。因此後端可以通過判斷請求頭中是否含有該屬性,來識別當前請求是否為 Ajax 請求。下面是手動設置該請求頭的示例。
<html>
<head>
<script language="javascript">
function cl(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "ajax2.html", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 手動設置 X-Requested-With 頭,模擬 Ajax 請求
xmlhttp.setRequestHeader('HTTP_X_REQUESTED_WITH', 'HTTP_X_REQUESTED_WITH');
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert(xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<input type="button" id="bt" name="bt" value="OK" onclick="cl();" />
</body>
</html>
後端讀取該請求頭即可判斷請求來源,常用於區分普通頁面跳轉與異步請求,從而返回不同的響應形式。