jQuery 默認在所有 AJAX 請求中添加 X-Requested-With: XMLHttpRequest 標頭,用於服務端識別 AJAX 請求。某些場景需移除:
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
beforeSend: function(xhr) {
// 關鍵:設置為空字符串函數,覆蓋默認值
xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
// 或直接刪除 (jQuery 內部允許)
// xhr.setRequestHeader('X-Requested-With', '');
},
success: function(data) {
console.log('無 X-Requested-With 請求成功:', data);
}
});
// 方式 1:ajaxSetup (影響所有後續 $.ajax)
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
}
});
// 方式 2:全局事件 ajaxSend (更靈活,可條件判斷)
$(document).on('ajaxSend', function(event, xhr, settings) {
// 可根據 URL 等條件決定是否移除
if (settings.url.indexOf('/third-party/') === 0) {
xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
}
});
// jQuery 內部發送標頭邏輯簡化
function setRequestHeader(xhr, name, value) {
// value 會被調用 toString()
xhr.setRequestHeader(name, value + ''); // 或 value.toString()
}
// 如果傳普通空字符串 ''
xhr.setRequestHeader('X-Requested-With', '');
// 瀏覽器實際發送:X-Requested-With: (空值,但標頭仍存在)
// 傳入對象,toString 返回空字符串
xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
// 瀏覽器發送:X-Requested-With: (空值)
// 某些瀏覽器/代理可能仍保留標頭名
// 徹底移除:原生 fetch / XMLHttpRequest 手動控制
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
// 簡單不設置該標頭即可
xhr.send();
若服務端依賴此標頭,移除後需協商替代方案:
| 方案 | 實現 | 優點 |
|---|---|---|
| 自定義標頭 | X-API-Request: true | 語義清晰、可控 |
| Content-Type | application/json 等 | REST 標準 |
| Query 參數 | ?format=json&ajax=1 | 簡單、可見 |
| Accept 標頭 | Accept: application/json | HTTP 標準 |
$.ajax({
url: '/api/user/profile',
type: 'POST',
data: {action: 'update'},
dataType: 'json',
headers: {
'X-API-Version': '2.1',
'X-Client-Id': 'web-app'
},
beforeSend: function(xhr) {
// 內部 API 保留 X-Requested-With,第三方 API 移除
if (this.url.indexOf('/third-party/') >= 0) {
xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
}
},
success: function(res) {
if (res.code === 0) showSuccess(res.data);
else showError(res.msg);
},
error: function(xhr, status, err) {
if (status === 'abort') return; // 手動取消不提示
showError('網絡錯誤: ' + err);
}
});
// fetch 默認不發送 X-Requested-With,完全可控
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Version': '2.1'
// 無 X-Requested-With,除非手動添加
},
credentials: 'include', // 攜帶 Cookie
body: JSON.stringify({key: 'value'})
}).then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
request.isAjax() (Spring/ThinkPHP/Laravel 等) 將返回 falseX-Requested-By: Fetch/jQuery,服務端按新標頭判斷X-Requested-With