Javascript get_headers : URLs : PHP functions in JavaScript JAVASCRIPT TUTORIALS


JAVASCRIPT TUTORIALS » PHP functions in JavaScript » URLs »

 

Javascript get_headers


fetches all the headers sent by the server in response to a HTTP request
Example 1

Running
1.get_headers('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');

Could return
1.'123'
function get_headers(url, format) {
    // fetches all the headers sent by the server in response to a HTTP request  
    // 
    // version: 812.1017
    // discuss at: http://phpjs.org/functions/get_headers
    // +   original by: Paulo Ricardo F. Santos
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.
    // *     example 1: get_headers('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    
    var req = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) throw new Error('XMLHttpRequest not supported');
    var tmp, headers, pair, i;

    req.open('HEAD', url, false);
    req.send(null);

    if (req.readyState < 3) {
        return false;
    }

    tmp = req.getAllResponseHeaders();alert(tmp);
    tmp = tmp.split('\n');
    tmp = array_filter(tmp, function (value) { return value.substring(1) != ''; });
    headers = [req.status + ' ' + req.statusText];

    for (i in tmp) {
        if (format) {
            pair = tmp[i].split(':');
            headers[pair.splice(0, 1)] = pair.join(':').substring(1);
        } else {
            headers[headers.length] = tmp[i];
        }
    }

    return headers;
}


HTML code for linking to this page:

Follow Navioo On Twitter

JAVASCRIPT TUTORIALS

 Navioo PHP functions in JavaScript
» URLs