主流 JS 庫 (jQuery、Prototype、YUI、Axios、Fetch 封裝) 在發送 AJAX 請求時,**自動加入**請求標頭:
X-Requested-With: XMLHttpRequest
// Servlet
boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
// Spring MVC
@GetMapping("/data")
public ResponseEntity> data(HttpServletRequest request) {
boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
if (isAjax) return ResponseEntity.ok(jsonData);
else return ResponseEntity.ok(viewPage);
}
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
app.use((req, res, next) => {
req.isAjax = req.xhr; // Express 內建屬性,基於 X-Requested-With
next();
});
// XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/data');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
// Fetch (需手動加標頭)
fetch('/api/data', {
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
function isAjaxRequest(headers) {
// headers: 物件或 Map,鍵不區分大小寫
const h = headers['x-requested-with'] || headers['X-Requested-With'];
return h === 'XMLHttpRequest';
}
// 使用範例 (Node/Express)
app.get('/test', (req, res) => {
if (isAjaxRequest(req.headers)) {
return res.json({ ajax: true, time: Date.now() });
}
res.render('page', { time: Date.now() });
});