Is gzip encoding compatible with JSON?

2019-03-19 16:52发布

问题:

I'm trying to narrow down some weirdness going on with my AJAX calls. My PHP scripts have this at the start:

ob_start("ob_gzhandler");

Works great with HTML. But are there any problems with doing it with application/json data? Any browser issues anyone is aware of?

回答1:

I don't think so... I've used static files stored as gzipped JSON before, and it worked fine with AJAX.

edit: I checked my php script and the only thing special I did was to include these headers:

Content-Encoding: gzip
Content-Type: text/plain

If I remember right, whenever I tried to change the Content-Type to something that would indicate JSON, the client had trouble.



回答2:

Some older browsers, like certain versions of IE6, screw up gzipped content, especially js content.

Just check that your server sends proper content-encoding header, that is

Content-Encoding: gzip

You should also check the headers sent by the browser for proper accept-encoding header before sending gzipped content... that is,

Accept-Encoding: gzip,deflate


回答3:

You can give out gzipped content whenever the browser specifies gzip in Accept-Encoding request header. In that case, there is no difference between JSON and HTML and no problems will be caused whatsoever.



回答4:

Instead of enabling compression in PHP, I would enable compression in Apache (using mod_deflate) so that you can check for various incompatible browsers and only send compressed data for the browsers that accept it and handle it correctly.

http://httpd.apache.org/docs/2.0/mod/mod_deflate.html