我有一个ajax脚本来发送数据。我想在发送/处理数据之前显示.coin-flip
3 秒。一旦这3秒结束,数据将被发送到翻转处理.php然后返回结果将显示在成功时。但目前它的速度如此之快,以至于我只能看到硬币在这里翻转(我想显示的动画(。因此,我希望在处理 ajax 请求之前延迟 3 秒。我该怎么做?
这是我的 ajax 脚本。
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val(),
};
$.ajax({
type: "POST",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#coins").hide();
$(".coin-flip").show();
},
success: function(html){
$(".message").html(html).fadeIn();
$("#coins").show();
$(".coin-flip").hide();
}
});
return false;
});
});
</script>
最简单的选择是在成功函数中使用超时,而不是延迟实际请求:
success: function(html){
setTimeout(function(){
$(".message").html(html).fadeIn();
$("#coins").show();
$(".coin-flip").hide();
},3000);
}
试试这个
setTimeout(function(){ callAjax(); }, 3000);
function callAjax(){
$.ajax({
type: "POST",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#coins").hide();
$(".coin-flip").show();
},
success: function(html){
$(".message").html(html).fadeIn();
$("#coins").show();
$(".coin-flip").hide();
}
});
return false;
}
只需在beforeSend
块中使用 setTimeout。
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val(),
};
$.ajax({
type: "POST",
url: "flip-process.php",
data: dataString,
cache: true,
success: function(html){
setTimeout(function(){
$(".message").html(html).fadeIn();
$("#coins").show();
$(".coin-flip").hide();
},3000);
}
});
return false;
});
});
</script>
你可以在超时中包装ajax调用
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val(),
};
var processing=false;
$.ajax({
type: "POST",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#coins").hide();
$(".coin-flip").show();
},
success: function(html){
$(".message").html(html).fadeIn();
$("#coins").show();
timeout = setTimeout(function(){
if (!processing)
{
processing=true;
$(".coin-flip").hide();
}
}, 2000}
});
);
return false;
});
});
</script>