How to handle ajax 201

后端 未结 5 1050
说谎
说谎 2020-12-31 09:16

When making a ajax call see example below success does gets a 201 status retuned. How do you handle these better i.e. 200, 201 within the succe

相关标签:
5条回答
  • 2020-12-31 09:57

    Instead of

    ResponseEntity<?> responseEntity = new ResponseEntity<>(HttpStatus.CREATED);
    

    I used

    ResponseEntity<?> responseEntity = new ResponseEntity<>(detailVO, HttpStatus.CREATED);
    

    Where detailVO is my object to rutrun in case of success. Then in browser I got response in success function.

    0 讨论(0)
  • 2020-12-31 10:03

    Use the statusCode object:

    var handle200 = function(data, textStatus, jqXHR) {
        alert('200'); // success codes have the success signature
    };
    
    var handle201 = function(data, textStatus, jqXHR) {
        alert('201'); // success codes have the success signature
        // test it if you are in doubt:
        console.log(data);
        console.log(textStatus);
        console.log(jqXHR);
    };
    
    var handle404 = function(jqXHR, textStatus, errorThrown) {
        alert('404'); // failing codes have the error signature
    });
    
    var request = $.ajax({
        type: 'POST',
        url: '/myresource/posttarget',
        data: { name: 'john' },
        statusCode: {
            200: handle200,
            201: handle201,
            404: handle404
        }
    });
    
    0 讨论(0)
  • 2020-12-31 10:03

    We had a similar problem; Looking at the jquery 1.9 source, a 201 status code expects content. If there is no content (or of the wrong content type) returned with the 201, then the fail callback is invoked.

    0 讨论(0)
  • 2020-12-31 10:12

    Data inserted successful but jquery still returning error

    The answer here appears to be a work around you can use for now. However, if you're using cross-domain, AJAX has some issues with that. Check out this SOF thread on it:

    Problems Reading the HTTP Status/Error Code from jQuery AJAX

    0 讨论(0)
  • 2020-12-31 10:17

    This is an old question but I'd like to comment anyway.

    I had the same problem and one thing that solved it for me was leaving the "dataType" unsetted. When you do this jQuery will try to guess the data type the server is returning and will not throw an error when your server returns a 201 with no content.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题