Ajax中的setRequestHeader設置請求頭
1、問題引發點:
前不久發現一個問題: 前端並沒有設置請求頭信息里面的Accept-Encoding:gzip...但是在請求頭中可以明顯的看到Accept-Encoding:gzip, deflate, sdch,並且我嘗試修改這個請求頭,發現 不 生 效;
2、XMLHttpRequest對象提供了一個設置請求頭的方法:setRequestHeader,對應的jQuery可以再beforeSend回調里面設置請求頭:
1 2 3 4 5 6 7 8 9 10 |
$.ajax({ type: "GET", url: "test.php", success: function(data) { console.log(data); }, beforeSend: function(xhr) { xhr.setRequestHeader("User-Agent", "headertest"); } }); |
3、后來看W3C標准文檔發現,這個請求頭不是什么都可以設置的,標准里面明確規定了以下請求頭信息是瀏覽器控制,開發者不允許設置這些請求頭
Terminate these steps if header is a case-insensitive match for one of the following headers:
- Accept-Charset
- Accept-Encoding
- Access-Control-Request-Headers
- Access-Control-Request-Method
- Connection
- Content-Length
- Cookie
- Cookie2
- Date
- DNT
- Expect
- Host
- Keep-Alive
- Origin
- Referer
- TE
- Trailer
- Transfer-Encoding
- Upgrade
- User-Agent
- Via
… or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-).
The above headers are controlled by the user agent to let it control those aspects of transport. This guarantees data integrity to some extent. Header names starting with Sec- are not allowed to be set to allow new headers to be minted that are guaranteed not to come fromXMLHttpRequest.
4、例子:
testAE.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html> <head> <title>test</title> </head> <script type="text/javascript" src="./jquery.1.8.1.min.js"></script> <body> <script type="text/javascript"> $.ajax({ type: "GET", url: "./testAE.php", success: function(data) { $("body").append(data); }, beforeSend: function(xhr) { xhr.setRequestHeader("Accept-Encoding", "testAE"); } }); </script> </body> </html> |
testAE.php
1 2 3 4 |
<?php /*回傳ACCEPT_ENCODING*/ echo $_SERVER['HTTP_ACCEPT_ENCODING']; ?> |
方法二:
headers: {
'token':'token_value'
},