修改html headers,javascript/jquery读取和修改HTTP headers

jQuery Ajax可以通过headers或beforeSend修改request的HTTP headers,例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Js代码

$.ajax({

url: "./test.php",

type: "POST",

headers: {

"Accept" : "text/plain; charset=utf-8",

"Content-Type": "text/plain; charset=utf-8"

},

/*

beforeSend: function(jqXHR, settings) {

jqXHR.setRequestHeader('Accept', 'text/plain; charset=utf-8');

jqXHR.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');

},

*/

data: {"user" : "min", "pass" : "he"},

error: function(jqXHR, textStatus, errorThrown) {

//....

},

success: function(data, textStatus, jqXHR) {

//....

}

}

注意::W3规定XMLHttpRequest并不能修改全部的HTTP Headers,而仅是一小部分。

比如:

Host: localhost:58188

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: keep-alive

role:2

username:106110454@qq.com

password:lw=kQH

password:1

jquery获取HTTP headers:

test.html:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

Html代码

$(document).ready(function(){

$.ajax({

url: "./test.php",

type: "POST",

data: {"user" : "min", "pass" : "he"},

error: function(jqXHR, textStatus, errorThrown) {

if (textStatus == "error") {

alert(textStatus + " : " +errorThrown);

} else {

alert(textStatus);

}

},

success: function(data, textStatus, jqXHR) {

alert(jqXHR.getResponseHeader("Server"));

alert(jqXHR.getResponseHeader("Content-Type"));

alert(jqXHR.getResponseHeader("X-Powered-By"));

alert(jqXHR.getResponseHeader("Content-Encoding"));

alert(jqXHR.getAllResponseHeaders());

alert(jqXHR.getResponseHeader("Set-Cookie"));       //返回null,不能获取Set-Cookie的值

alert(data + textStatus);

}

});

});

.php:

if (isset($_COOKIE["time"])) {

$time = $_COOKIE["time"] + 1;

} else {

$time = 1;

}

setcookie("time", $time);

$user = $_REQUEST["user"];

$pass = $_REQUEST["pass"];

print $user.$pass." ".$time;

jQuery通过XMLHttpRequest的getResponseHeader或getAllResponseHeaders()可以获取指定的HTTP header field的值,但规定不能获取Set-Cookie和Set-Cookie2的值。

参考:

http://stackoverflow.com/questions/1145588/cannot-properly-set-the-accept-http-header-with-jquery

http://stackoverflow.com/questions/2444489/getresponseheader-is-not-a-function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值