简体   繁体   中英

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. The first one is a textual application/json , in which case I want a string or an already parsed object; and the second one is a binary application/zip , in which case I want a Blob that I can then process with 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. Is there a better way? Browser compatibility requirement: IE10+ and the latest whatever else.

The simplest approach would be to set .responseType to Blob , check .type of .response . If .type is "application/json" , use FileReader.prototype.readAsText() to get JSON , else use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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