$something=100;
$.ajax({
type: "post",
url: "some.php",
data: somevariable,
dataType: "text",
success: function(data) {
$something=$something-10;
alert($something);
}.bind(this)
});
以上ajax用于从some.php文件中获取数据,该文件用于从mysql数据库中获取数据。当成功或从数据库中检索到数据时,该文件会发出一条消息提醒,但即使我停止 mysql 服务器然后再次调用 ajax,它也会提醒消息 $something 的值减少
那么我怎样才能让它像没有从数据库返回行或空行那样工作,那么只有当从数据库返回一些实际数据时才应该没有成功才算成功?
最佳答案
你可以这样做:-
success: function (data) {
// Checking data is not null or undefined and valid data is returned
if (data && data.length > 0) {
$something = $something - 10;
alert($something);
}
}
假设 data
是从服务器返回的数据数组。
此外,为了安全起见,请使用延迟 jqXHR.fail()
之类的
$.ajax("some_unknown_page.html")
.fail(function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
});
这将帮助您找出从服务器返回数据时发生的具体错误,然后您可以采取适当的措施。
或者,作为一个简单的例子:-
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});
关于php - 即使没有成功,Ajax 成功功能仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32283648/