[英]How to get the jQuery $.ajax error response text?
我正在向我的 jQuery 发送错误响应。 但是,我无法获得响应文本(在下面的示例中,这将是Gone to the beach )
jQuery 唯一说的是“错误”。
有关详细信息,请参阅此示例:
php
<?
header('HTTP/1.1 500 Internal Server Error');
print "Gone to the beach"
?>
jQuery
$.ajax({
type: "post",
data: {id: 0},
cache: false,
url: "doIt.php",
dataType: "text",
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
success: function () {
alert(" Done ! ");
}
});
现在我的结果是:
日志:
[XMLHttpRequest readyState=4 status=500, "error", undefined]
警报:
不能这样做,因为:错误
有任何想法吗?
尝试:
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
对我来说,这很有效:
error: function(xhr, status, error) {
alert(xhr.responseText);
}
查看请求参数的responseText
属性。
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.Message);
}
最好的简单方法:
error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
这对我有用
function showErrorMessage(xhr, status, error) {
if (xhr.responseText != "") {
var jsonResponseText = $.parseJSON(xhr.responseText);
var jsonResponseStatus = '';
var message = '';
$.each(jsonResponseText, function(name, val) {
if (name == "ResponseStatus") {
jsonResponseStatus = $.parseJSON(JSON.stringify(val));
$.each(jsonResponseStatus, function(name2, val2) {
if (name2 == "Message") {
message = val2;
}
});
}
});
alert(message);
}
}
如果您想获得带有行号的语法错误,请使用此
error: function(xhr, status, error) {
alert(error);
}
这将允许您查看整个响应,而不仅仅是“responseText”值
error: function(xhr, status, error) {
var acc = []
$.each(xhr, function(index, value) {
acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));
}
你也可以试试:
$(document).ajaxError(
function (event, jqXHR, ajaxSettings, thrownError) {
alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
});
我用过这个,效果很好。
error: function(xhr, status, error){
alertify.error(JSON.parse(xhr.responseText).error);
}
err.responseText
包含 HTML 标签,您可以轻松地从这些标签中获取错误消息...
例如:
$(err.responseText)
// k.fn.init(12) [text, title, text, meta, text, style, text, span, text, font, text, //comment]
$.ajax({
async: bAsync,
type: 'POST',
url: pUrl,
contentType: 'application/json; charset=utf-8;',
dataType: 'json',
data: pData,
success: fn,
error: function(err) {
alert( $($(err.responseText)[1]).text() )
debugger;
}
});
试试这个在控制台中有完整的错误细节。
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error Thrown: "+errorThrown);
console.log("Text Status: "+textStatus);
console.log("XMLHttpRequest: "+MLHttpRequest);
console.warn(xhr.responseText)
}
如果您没有遇到网络错误,并且想从后端显示错误,例如权限不足,请使用 200 和错误消息来响应您的响应。 然后在您的成功处理程序中检查 data.status == 'error'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.