如果在发送请求之前动态地将XMLHttpRequest
设置为json
,那么是否有可能从responseType
响应中获取“原始”(文本/数据)?
我认为可以有条件地使用overrideMimeType
对同一个URL进行另一个请求,但这可能是不明智的--对于服务器日志或任何其他进程。
下面是一个示例:
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();
在我的项目的实际代码中,对“/文件夹/path/”的请求被视为对JSON的请求,服务器使用JSON进行响应;除非出现问题,或者调用client.console.log()
例程进行调试/测试。
如有任何意见将不胜感激,谢谢。
发布于 2017-02-05 07:17:24
以下是该问题的解决方案;然而,这是一个解决方案-but 可能会对面临相同问题的其他人有所帮助:
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();
https://stackoverflow.com/questions/42002819
复制相似问题