X-Requested-With 這個標頭常用來判斷請求是否為 ajax 而來。但有些時候,我們反而需要把它移除。以下介紹一種做法。
$.ajax({
url: 'https://www.zhangruifeng.com',
beforeSend: function( xhr ) {
xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
},
success: function( data ) {
if (console && console.log){
console.log( 'Got data without the X-Requested-With header' );
}
}
});
關鍵在 beforeSend 這個環節:它讓我們能在請求發出前拿到原生的 XMLHttpRequest 物件,進而透過 setRequestHeader 把 X-Requested-With 的值覆寫為空字串。
在 Java 端,判斷是否為 ajax 請求的常見寫法如下:
if (request.getHeader("x-requested-with") != null
&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
//異步請求
}else{
//一般請求
}
理解了伺服器端如何判斷,就能明白為何有時需要在前端刻意移除這個標頭——例如要模擬一般表單請求,或避開某些依賴此標頭的中間層過濾。