在进行ajax通话时,请参阅下面的示例success
确实会重新获得 201 状态。你如何更好地处理这些,即成功函数中的200,201?
$.ajax({
type: "POST",
dataType: "json",
url: "http://api.domain.com/sms",
data: {
// Send value in mobile input field.
mobile: $("#mobile").val(),
},
// On successful AJAX call do the following.
success: function(data) {
$('#messageText').text('SMS successfully sent');
},
error: function(jqXhr) {
data = JSON.parse(jqXhr.responseText);
}
});
答案 0 :(得分:12)
使用statusCode
对象:
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
}
});
答案 1 :(得分:6)
这是一个老问题,但无论如何我想发表评论。
我遇到了同样的问题,有一件事让我解决了这个问题,就是让“dataType”不受限制。执行此操作时,jQuery将尝试猜测服务器返回的数据类型,并且在服务器返回201但没有内容时不会抛出错误。
希望它有所帮助。
答案 2 :(得分:0)
Data inserted successful but jquery still returning error
这里的答案似乎是你现在可以使用的解决方法。但是,如果您使用跨域,则AJAX存在一些问题。看看这个SOF帖子:
Problems Reading the HTTP Status/Error Code from jQuery AJAX
答案 3 :(得分:0)
我们遇到了类似的问题;查看jquery 1.9源代码,201状态代码需要内容。如果201中没有返回内容(或错误的内容类型),则调用失败回调。
答案 4 :(得分:0)
代替
ResponseEntity<?> responseEntity = new ResponseEntity<>(HttpStatus.CREATED);
我用过
ResponseEntity<?> responseEntity = new ResponseEntity<>(detailVO, HttpStatus.CREATED);
如果成功,detailVO是我的目标。然后在浏览器中,我得到了成功功能的响应。