javascript之Ajax获取和设置标头

XMLHttpRequest对象中与标头有关的方法:

setRequestHeader(<header>,<value>)——用指定值设置标头。

getResponseHeader(<header>)——获取指定标头的值;

getAllResponseHeaders()——以单个字符串形式获取全部标头。


覆盖请求的HTTP方法,例如以下代码:可规避防火墙仅仅同意GET和POST请求通过的限制;

httpRequest.setRequestHeader("X-HTTP-Method-Override","DELETE");
禁用内容缓存:

httpRequest.setRequestHeader("Cache-Control","no-cache");

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>上海远地资产管理有限公司</title>
    <meta name="author" content="jason"/>
    <meta name="description" content="上海远地资产管理有限公司(简称:远地资产),是一家专业的互联网金融服务平台."/>
    <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon"/>
    <style type="text/css">
        #allheaders,#ctheader{
            border: medium solid black;
            padding: 2px;
            margin: 2px;
        }
    </style>
</head>
<body>
    <div>
        <button>Apples</button>
        <button>Cherries</button>
        <button>Bananas</button>
    </div>
    <div id="ctheader"></div>
    <div id="allheaders"></div>
    <div id="target">
        载入内容
    </div>

    </table>
    <script>
        var buttons=document.getElementsByTagName("button");
        for(var i=0;i<buttons.length;i++){
            buttons[i].onclick=handleButtonPress;
        }
        var httpRequest;
        function handleButtonPress(e){
            httpRequest=new XMLHttpRequest();
            httpRequest.onreadystatechange=handleResponse;
            httpRequest.open("GET", e.target.innerHTML+".html");
            //规避防火墙的限制,使用X-HTTP-Method-Override标头来指定想要的HTTP方法,但形式上市再发送一个POST请求
            //httpRequest.setRequestHeader("X-HTTP-Method-Override","DELETE");
            //禁用内容缓存
            //httpRequest.setRequestHeader("Cache-Control","no-cache");
            httpRequest.send();
        }
        function handleResponse(){
            if(httpRequest.readyState==2){
               document.getElementById("allheaders").innerHTML=httpRequest.getAllResponseHeaders();
                document.getElementById("ctheader").innerHTML=httpRequest.getResponseHeader("Content-Type");
            }else if(httpRequest.readyState==4 && httpRequest.status==200){
                document.getElementById("target").innerHTML= httpRequest.responseText;
            }
        }

    </script><pre name="code" class="html"></body>
</html>





posted @ 2017-07-21 14:21  yxysuanfa  阅读(633)  评论(0编辑  收藏  举报