2017-03-29 100 views
0

我有一个ajax脚本来发送数据。我想在数据发送/处理之前显示.coin-flip 3秒钟。一旦这3秒结束,数据将正常发送到flip-process.php,然后返回结果将显示成功。但目前速度非常快,我只能看到硬币在这里翻转(我想要显示的动画)。因此,我希望在处理ajax请求之前延迟3秒。我该怎么做?在处理之前延迟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> 
+1

使用的setTimeout方法为它 的setTimeout(函数(){//动作东西},3000); –

回答

4

的easist选项将是你成功的函数使用超时,而不是延迟实际的请求:

success: function(html){ 
    setTimeout(function(){ 

     $(".message").html(html).fadeIn(); 
     $("#coins").show(); 
     $(".coin-flip").hide(); 

    },3000); 
} 
+0

完美解决方案...:D –

0

你可以用在超时Ajax调用

+0

这隐藏了整个事情三秒钟..我想显示在'beforeSend'内的'.coin-flip'显示3秒,然后隐藏并显示结果最终.. –

+0

检查更新的答案 –

0

只需在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> 
0

尝试此

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; 
}