通过AJAX检索blob时处理错误消息 [英] Handling error messages when retrieving a blob via AJAX

查看:3831
本文介绍了通过AJAX检索blob时处理错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据服务器的响应执行可能返回blob或文本字符串的AJAX调用?

我是使用AJAX将用户提供的视频转换为音频blob(用于< audio> 标记)。转换过程运行正常,但视频可能有问题,在这种情况下,服务器将返回HTTP状态代码500,响应正文中的错误消息为纯文本。在这种情况下,我需要响应的明文,但尝试使用responseText会导致此错误消息:

I'm using AJAX to convert a user-supplied video to an audio blob (for use in an <audio> tag). The conversion process works fine, but it's always possible that there could be something wrong with the video, in which case the server will return an HTTP status code of 500 with the error message in the response body as plaintext. In that case, I need the plaintext of the response, but trying to use responseText results in this error message:

Uncaught InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

这是我当前代码的简化版本:

Here's a simplified version of my current code:

function convertToAudio(file) {
    var form = new FormData();
    form.append("Video", file, file.name);

    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if(request.readyState == 4 && request.status == 200) {
            console.log(typeof request.response); // should be a blob
        } else if(request.readyState == 4 && request.responseText != "") {
            console.log(request.responseText);
        }
    };
    request.open("POST", "video_to_audio", true);
    request.responseType = "blob";
    request.send(form);
}

我在我的代码中使用jQuery(所以jQuery答案是可以接受的),但据我所知,jQuery不处理blob。

I am using jQuery elsewhere in my code (so jQuery answers are acceptable), but as far as I know jQuery doesn't handle blobs.

推荐答案

当readyState为2时设置responseType。

可以在 readyState之前的任何时间更改 responseType 达到3.当 readyState 达到2时,您可以访问响应标头以做出决定。

The responseType value can be changed at any time before the readyState reaches 3. When the readyState reaches 2, you have access to the response headers to make that decision with.

更新了示例代码:

function convertToAudio(file) {
    var form = new FormData();
    form.append("Video", file, file.name);

    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if(request.readyState == 4) {
            if(request.status == 200) {
                console.log(typeof request.response); // should be a blob
            } else if(request.responseText != "") {
                console.log(request.responseText);
            }
        } else if(request.readyState == 2) {
            if(request.status == 200) {
                request.responseType = "blob";
            } else {
                request.responseType = "text";
            }
        }
    };
    request.open("POST", "video_to_audio", true);
    request.send(form);
}

这篇关于通过AJAX检索blob时处理错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆