我知道我的问题是jQuery试图将响应的主体解析为json,但主体是未定义的,因此抛出了一个错误。
我无法改变回应。这是Jenkins服务器的默认响应。它在头中发送一个201、404或500,我想处理它。
我的ajax:
$(document).ready(function () {
$('#reviewForm').bootstrapValidator({
...stuff...
...validation...
})
.on('success.form.bv', function (e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Use Ajax to submit form data
$.ajax({
type: 'POST',
url: url+$form.serialize(),
dataType: 'text',
complete: function() {
alert("Success.");
},
error: function(xhr, status, text) {
alert("failure");
}
});
尽管发布成功(创建了201),但由于未定义的正文导致语法错误,它仍然会出错。
我很乐意处理错误中的错误:ajax的一部分,但我一辈子都不知道如何从响应的头部获取状态代码。
正如我所说,如果可以的话,我会改变回应,但这正是詹金斯的工作方式。
谢谢。
EDIT:响应标头
Status Code: 201 Created
Connection: Keep-Alive
Content-Type: text/plain; charset=UTF-8
Date: Wed, 01 Oct 2014 14:51:12 GMT
Keep-Alive: timeout=15, max=100
Location: https://jenkins....
Server: Jetty(8.y.z-SNAPSHOT)
Transfer-Encoding: chunked
这就是xhr(xml http响应)
{
"readyState": 0,
"status": 0,
"statusText": "error"
}
您可以对状态代码进行特定的回调,例如:
$.ajax({
...
statusCode: {
201: function() { /* I received a 201 */ },
404: function() { /* I received a 404 */ },
500: function() { /* I received a 500 */ }
}
});
这在文档中列出
状态代码决定jQuery将触发哪个函数(即complete
、error
或success
)。
所以,试试这个:
$.ajax({
type: 'POST',
url: url,
dataType: 'text',
complete: function(response) {
console.log(response);
});
在将来,这将使您能够更好地进行调试。(通过您的检查元件控制台)
但是,在本例中,状态代码将在中
response.status
error
函数将对任何不是200的函数进行激发,因此您最好只使用完整函数,只需将错误放在switch-case
语句的default
块中。。。
[...]
complete: function(response){
switch(response.status){
case 201:
alert("success"
break;
default:
alert("Something unexpected occurred");
break;
}
只需使用complete
处理程序-它将在调用success
或error
之后运行。无论哪种方式,对于complete
和error
,第一个参数都是jqXHR
对象,它具有status
属性,该属性将为您提供响应的状态。
$.ajax({
type: 'POST',
url: url,
dataType: 'text',
complete: function(xhr) {
//this handler runs regardless of success or error
//query xhr.status for the response code
}
});
您可以使用statusCode
$.ajax({
type: 'POST',
url: url,
statusCode: {
200: function (response) {
alert('200');
},
201: function (response) {
alert('201');
},
404: function (response) {
alert('400');
}
}, success: function () {
alert('Success');
},
});
如果我是认真的,你想检查来自服务器(201200500)的响应:可能使用.awlways()
$.ajax({
type: 'POST',
url: url,
dataType: 'text',
always: function(status){
alert(status);
}
});
或者u可以在xhr对象上使用getAllResponseHeaders()
?