How to get the Ajax header fields in javascript?

1.3k views Asked by At

I am using the following to do a http GET:

$.ajax({
    type: 'GET',
    url: server + '/hello',
    dataType: 'json',
    async: false,
    xhrFields: {
        withCredentials: true
    },

    success: function(data){
        if(data.connected){
    },
    error: function(a, b, c){
    }
});

I see these are set in the headers:

 Accept:application/json, text/javascript, */*; q=0.01
 Accept-Encoding:gzip,deflate,sdch
 Accept-Language:en-US,en;q=0.8
 Authorization:Basic bGlkerrdN1NDpTdW55ytXIwMA==
 Connection:keep-alive 
 Cookie:OBBasicAuth=fromCache; 
 ObSSOCookie=
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.10 Safari/537.36
 Response Headersview source

IS there a way in Javascript or JQuery I can get the Authorization part?

2

There are 2 answers

0
Pritam Banerjee On BEST ANSWER

Could not get that to work in JavaScript.

Got that working on the server side, where I grabbed the details from the headers, by using @context HttpServletRequest. Then grabbed the headers and sent the required parameters back to the client.

That was the only way to do it, as far as I read it from other sources, because JavaScript does not have access to these cookies and headers which are set by the browser.

7
codeGig On

Here is an example how to set and get header in ajax call

$.ajax({
            type:"POST",
            beforeSend: function (request)
            {
                request.setRequestHeader("Token", authorizationToken);
            },
            url: "entities",
            data: "json=" + escape(JSON.stringify(createRequestObject)),
            processData: false,
             success: function(data, textStatus, request){
                  alert(request.getResponseHeader('some_header'));
             },
    });