Search code examples
javascriptjqueryheaderresponse

jquery How can i get headers key value?


I want to get headers key and value in response. In the image below you can see header response data. There is a key named documentname recieved from server in header.

enter image description here

How can i get this key and value in jquery ?

Update

I am using Syncfusion Component and headers is not ajax call response :

<ejs-uploader id="UploadFiles" success="onuploadSuccess" autoUpload=false></ejs-uploader> 

<script>
    function onuploadSuccess(args){
        console.log(args.response);
    }
</script>

Solution

  • You're receiving a non standard string in your object.headers. That being said you'll have to manually tear it down.

    1. Split it based on newline \r\n
    2. Filter the array and search for documentname
    3. Pluck the element you want (should be the ONLY element) --> [0]
    4. Split on : (space included, unless you want to trim(), Either works here)

    You will end up with

    ["documentname", "sdfasfjhkjsdfhkjsdf.png"]
    

    You can go a step further and break them down to key and value -- Then you can do whatever you wish with them ... Create an object, or handle them individually as strings.

    I recreated my_object to provide a working example.. Just replace the my_object.headers with args.response.headers.

    const my_object = {
    headers:"content-length: 0\r\ndate: Wed, Dec 6 2023 22:28:37 GMT\r\ndocumentname: sdfasfjhkjsdfhkjsdf.png\r\nserver: Kestral\r\n", 
    readyState:40, 
    statusCode:200, 
    statusText:"",
    withCredentials:false
    };
    
    const docArr = my_object.headers
        .split('\r\n')
        .filter(element => element
        .includes("documentname"))[0]
        .split(': ');
        
    
    console.log(docArr)
    
    const key = docArr[0];
    const value = docArr[1];
    
    console.log('key is: ' + key + ' and value is: ' +  value)