如何从$ ajax获取响应代码错误?

时间:2017-08-14 19:22:37

标签: javascript json ajax

我想获取代码,例如下面的代码:

  

(500)。

并且还要经历此错误,以便能够显示" Code"," requestID"和"消息"。

以下是我的代码的一些示例以及用户可能出现的错误。

代码示例:

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
            "visualFeatures": "Categories",
            "details": "{string}",
            "language": "en",
        };

        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
            },
            type: "POST",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>

错误代码:

Response 500

Possible Errors:

FailedToProcess 
Failed to process the image.
Timeout 
Image processing time out.
InternalServerError 
Internal server error.

application/json
{
        "code":"FailedToProcess",
    "requestId":"B8D802CF-DD8F-4E61-B15C-9E6C5844CCBC",
    "message":"Could not extract image features"
}

1 个答案:

答案 0 :(得分:0)

可以像这样检索响应代码:

.fail(function(jqXHR, textStatus, errorThrown) {
         alert(jqXHR.status);
 })

其他属性也存在,您可以在此处阅读:http://api.jquery.com/jQuery.ajax/