22
votes

I have a web service that is willing to output gzip/deflated data. I've verified that the service will respond with raw JSON or with gzip'd JSON using wget and curl.

I want to consume this web service using the jQuery AJAX call.

By default, the $.ajax call that jQuery provides does not add the "Accept-Encoding: gzip" HTTP request header that's necessary for the web server to respond with gzipped data.

However, when I use jQuery's own methods to add the header, eg:

$.ajax({url: 'http://foo.com/service.json',
        beforeSend: function(xhr) { 
            console.log('xhr set'); 
            xhr.setRequestHeader('Accept-Encoding', 'deflate') 
       } 
});

then the following error appears in the browser console:

Refused to set unsafe header "Accept-Encoding"

Is it possible to force jQuery to make AJAX calls for URLs with gzip/deflate enabled?

If not, is this a shortcoming in jQuery, or something more fundamental with AJAX?

1
I think the browser decides wether it accepts gzip/deflate or not. "Faking" this could lead to data corruption.jwueller

1 Answers

41
votes

Browsers automatically add the accept-encoding header as appropriate, including on XHR requests. You don't need to do that at the DOM/JS level.