简体   繁体   中英

How do I access the JSON response with jQuery.Ajax for a 400 error?

In jQuery, I'm submitting forms to the server. When there is a validation error, I receive a 400 error from the server, and the body of the document is valid JSON. I would like to know how to access the data returned from the server.

My .error callback function on the jQuery.Ajax object is never called, so I'm using .statusCode{400} function. This runs just fine, however none of the arguments contain the response body.

Some browsers' XHR implementations refuse to provide the response body if the HTTP status is not 2xx. What I've had to resort to in API design where I couldn't control my clients was to do something like always return 200 and indicate success/failure/status in some other way (eg, as a top-level attribute in the JSON response).

I try to get json response with a status 400, and it works on IE7,8 and 9, Firefox and Chrome (Safari not tested).

...
error: function(xhr) {
   error(xhr.responseText);
}
...

I have had no trouble using statusCode in the callback, However, statusCode as a callback function Does NOT return any data.

jQuery.Ajax

I think you should try a different approach on how to handle validation errors in the server side, to return status code 200, but with a parameter like "error_count" and go from there.

can you post some of the code you are using (just $.ajax you are using...) ?

For me (Chrome), responseText property of the xhr response contains only "BAD REQUEST" when statusCode is 400. Thanks Steven for your response; I was struggling with this since in Postman I could get the json data I was returning from my REST controller, but couldn't find it on the jQuery Ajax response.

"If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object. "

http://api.jquery.com/jquery.ajax/

If you're specifying your callback with statusCode as mentioned in the question:

"If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. " (jqXHR, textStatus, errorThrown)

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