在旧版本的jQuery中。有时我使用 jQuery ajax 并设置 async:false 来等待来自 ajax 的响应。但在今天,async:false 已被弃用。我不知道如何使用其他代替 async:false。请建议我。
[当我使用 jQuery ajax async:false 时我的代码]
function check(id) {
var check = '';
jQuery.ajax({
type : 'post',
url : 'test.php',
data : 'id='+id,
cache:false,
async:false,
success:function(data) {
if(data == 'good') {
check = 'pass';
}
else
if(data == 'bad') {
check = 'not_pass';
}
}
});
if(check == 'pass') {
alert('Pass');
}
else
if(check == 'not_pass') {
alert('Not pass');
}
}
在上面的代码中,我使用 async:false 来等待来自 test.php 的响应。测试后.php但不推荐使用 async:false。
>async: false
总是很少使用,因为它在等待服务器响应时会阻止所有用户输入。异步处理结果要好得多,例如:
jQuery.ajax({
type : 'post',
url : 'test.php',
data : 'id='+id,
cache:false
})
.done(function(data) {
if (data == 'good') {
alert('Pass');
}
else if (data == 'bad') {
alert('Not pass');
}
})
.error(function() {
//handle the error...
});
请注意,我还使用新的 Promise 接口(done()
和 error()
回调)。如果您愿意,success
和error
选项仍然有效。