`
wanxiaotao12
  • 浏览: 456178 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

javascript/jquery读取和修改HTTP headers

 
阅读更多

javascript/jquery读取和修改HTTP headers

jquery修改HTTP headers

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

    $.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,而仅是一小部分。

jquery获取HTTP headers:

test.html:

    <html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    </head>
    <body></body>
    <script type="text/javascript">
    $(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);
            }
        });
    });
    </script>
    </html>

test.php:

    <?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的getResponseHeadergetAllResponseHeaders()可以获取指定的HTTP header field的值,但规定不能获取Set-CookieSet-Cookie2的值

参考:

<!--EndFragment-->

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics