简体   繁体   中英

How to handle 204 response from ajax request in jquery

I'm trying to handle a Status: HTTP/1.1 204 No Content error. I'm using .fail() to handle all other errors, but 204 is not handled by this function. While trying if (jqXHR.status == "204") {alert("error!");} , the alert is not thrown when a 204 is received.

$.ajax({
    url: url,
    method: 'GET',
    headers: {
        "Authorization": bearerToken
    },
}).then(function(response) {
    var obj = response;
    $("#imageid").css("border-color", "#ccc");
    $(".search-results").empty();
    for (var property in obj.entity.entries) {
        if (obj.entity.entries.hasOwnProperty(property)) {
            $(".search-results").append($("<li><a href='" + obj.entity.entries[property].uri + "' target='_blank'><div class='thumbnail'><img width='30' height='30' src='" + obj.entity.entries[property].uri + "' target='_blank'/></img><div class='caption'><p>" + obj.entity.entries[property].orientation + "</p></div></a></li>"));
        }
    }
    //$(".search-results").append("<div class='caption'>" + data.id + "</div><div class='thumbnail'><img width='40' height='40' src='" + data.thumbnailUrl + "'/></img>").css("float", "left");
}).fail(function(data, jqXHR) {
    if (jqXHR.status == "204") {
        $(".search-results").empty();
        $(".search-results").append("<p class='alert alert-danger'>Invalid ID</p>");
        $("#imageid").css("border-color", "red");
    }
    $(".search-results").empty();
    $(".search-results").append("<p class='alert alert-danger'>Invalid ID</p>");
    $("#imageid").css("border-color", "red");
});

2xx is considered success. Your success function should be getting called. Check the status code there.

jqXHR is the 3rd argument to the success callback.

Edit: here's code

then(function(data, responseText, jqXHR) {
  if(jqXHR.status == 204) alert('no content')
})

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