简体   繁体   English

如果我不知道响应类型,可以执行XMLHttpRequest吗?

[英]Can I perform an XMLHttpRequest if I don't know the response type?

I wish to perform an XMLHttpRequest to GET a resource, but the catch is that the resource can be in two different formats, and I don't know which one. 我希望执行XMLHttpRequestGET资源,但是要注意的是该资源可以采用两种不同的格式,但我不知道哪种格式。 The first one is a textual application/json , in which case I want a string or an already parsed object; 第一个是文本application/json ,在这种情况下,我需要一个string或一个已经解析的对象; and the second one is a binary application/zip , in which case I want a Blob that I can then process with JSZip. 第二个是二进制application/zip ,在这种情况下,我需要一个Blob ,然后可以使用JSZip处理它。 I could always request it as a Blob , check the response headers, and then use a FileReader to convert it to a string if necessary, but this feels kinda clunky. 我总是可以将其请求为Blob ,检查响应头,然后在必要时使用FileReader将其转换为string ,但这有点笨拙。 Is there a better way? 有没有更好的办法? Browser compatibility requirement: IE10+ and the latest whatever else. 浏览器兼容性要求:IE10 +和最新版本。

The simplest approach would be to set .responseType to Blob , check .type of .response . 最简单的方法是将.responseType设置为Blob ,检查.response .type If .type is "application/json" , use FileReader.prototype.readAsText() to get JSON , else use Blob .response . 如果.type"application/json" ,则使用FileReader.prototype.readAsText()获取JSON ,否则使用Blob .response

You can also perform a HEAD request before the actual request, check Content-Type header to determine how to process response of actual request. 您还可以在实际请求之前执行HEAD请求,检查Content-Type标头以确定如何处理实际请求的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM