$something=100;
$.ajax({
type: "post",
url: "some.php",
data: somevariable,
dataType: "text",
success: function(data) {
$something=$something-10;
alert($something);
}.bind(this)
});
上面的ajax用于从一些.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
是从服务器返回的数据数组。另外,为了安全起见,使用延迟
$.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" );
});