Reputation:
Is it possible to get the "raw" (text/data) from an XMLHttpRequest
response if the responseType
was dynamically set to json
prior to sending the request?
I suppose it could be done conditionally with another request to the same URL with overrideMimeType
, but that could be unwise - regarding server logs or any other processes.
Here is an example:
var xhr = new XMLHttpRequest();
xhr.open('GET','/some/path.wtf');
xhr.responseType = 'json';
xhr.onloadend = function()
{
if (this.status !== 200)
{
console.log(this.response); // null
// send the response-text to an error handler .. sigh :(
return;
}
};
xhr.send();
In the actual code of my project, a request for a "/folder/path/" is regarded as a request for JSON and the server responds with JSON; unless there was an issue, or a client.console.log()
routine was invoked for debugging/testing.
Any input will be appreciated, thank you.
Upvotes: 2
Views: 1916
Reputation:
The following is a solution to the problem; however, it is a work-around -but may be helpful to others facing the same problem:
var pth,ext,rsp,xhr;
pth = '/some/path/';
rsp = ((path.substr(-1) == '/') ? 'json' : 'blob'); // for example
xhr = new XMLHttpRequest();
xhr.patchJSON = ((rsp == 'json') ? 1 : 0);
xhr.open('GET',pth);
xhr.responseType = ((rsp == 'json') ? 'text' : rsp);
xhr.onloadend = function()
{
if (this.status !== 200)
{
console.log(this.response); // response-text from server
// send the response-text to an error handler .. yayy :)
return;
}
if (this.patchJSON)
{
rsp = JSON.parse(this.response);
if ((rsp === null) && (this.response.trim().length > 0))
{
console.log('json syntax error in: '+pth);
// send `rsp` to the error handler
return;
}
}
// handle blobs/markup/etc, -or:
console.log(rsp);
};
xhr.send();
Upvotes: 1