I want to delay jQuery ajax successful function

元气小坏坏 提交于 2019-12-13 07:46:08

问题


I want to let user wait for 2 seconds before the HTML inside the block changes. Can you help me to set some time so that ajax request was not so fast and I had time to show some animation

I tried to set timeout but it is not working

jQuery(document).ready( function($) {

$(document).on('click', '#wp-request', function(event){
	            event.preventDefault();	
            	var path = myScript.pluginsUrl + '/simple/widget-final.php';
				$.ajax({
					 type : 'POST',
                                         url: path,
                                         cache: false,
					 success : function(data){
					 var newWidget = $(data); 
					 $('#widget-container').replaceWith(newWidget);
					 },
					 error : function(){ alert('Error'); },
					 dataType : 'html'
                });
				
});

$(document).on('click', '#wp-back', function(event){
				event.preventDefault();
				var path = myScript.pluginsUrl + '/simple/widget-initial.php';
				$.ajax({
					 type : 'POST',
                                         url: path,
                                         cache: false,
					 success : function(data){
					 var newWidget = $(data); 
					 $('#widget-container').replaceWith(newWidget);
					 },
					 error : function(){ alert('Error'); },
					 dataType : 'html'
                });
				
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="widget-container">
<p>We are on first page</p>
<a id="wp-request" href="">Send</a>
</div>

回答1:


Just use setTimeout in your success callback function.

success : function(data){
    setTimeout(function(){
         var newWidget = $(data); 
         $('#widget-container').replaceWith(newWidget);
     },2000);  // The millis to wait before executing this block
},


来源:https://stackoverflow.com/questions/40829915/i-want-to-delay-jquery-ajax-successful-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!