是否可以强制 jQuery 对启用了 gzip/deflate 的 URL 进行 AJAX 调用? [英] Is it possible to force jQuery to make AJAX calls for URLs with gzip/deflate enabled?
问题描述
我有一个愿意输出 gzip/deflated 数据的网络服务.我已经验证该服务将使用原始 JSON 或使用 wget 和 curl 的 gzip JSON 进行响应.
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.
我想使用 jQuery AJAX 调用来使用这个网络服务.
I want to consume this web service using the jQuery AJAX call.
默认情况下,jQuery 提供的 $.ajax 调用不会添加Accept-Encoding: gzip"HTTP 请求标头,这是 Web 服务器响应 gzip 数据所必需的.
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.
但是,当我使用 jQuery 自己的方法添加标题时,例如:
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"
是否可以强制 jQuery 对启用了 gzip/deflate 的 URL 进行 AJAX 调用?
Is it possible to force jQuery to make AJAX calls for URLs with gzip/deflate enabled?
如果不是,这是 jQuery 的一个缺点,还是 AJAX 的一些更基本的东西?
If not, is this a shortcoming in jQuery, or something more fundamental with AJAX?
推荐答案
浏览器会根据需要自动添加 accept-encoding 标头,包括在 XHR 请求上.您不需要在 DOM/JS 级别执行此操作.
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.
这篇关于是否可以强制 jQuery 对启用了 gzip/deflate 的 URL 进行 AJAX 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!