用ajax的时候遇到网速很慢的时候,要给一个温馨 提示,例如"正在加载中"的效果 低于1.8的版本可以使用如下方法: $('.loading').ajaxStart(function(){ $(this).show(); }).ajaxStop(function(){ $(this).hide(); }); 1.8以后的版本使用这样 $(document).ajaxStart(function(){ $('.loading').show(); //ajax还没加载完就执行这里 }).ajaxStop(function(){ $('.loading').hide(); //ajax加载完就执行这里 }); ajaxStart和ajaxStop是全局事件。 错误提示 适用于$.ajax的错误提示 $.ajax({ type:'POST', //ajax选择POST方式提交数据 url:'use.php', //将数据提交到这个文件 data:$('form').serialize(), //获取到form中所有提交的数据 success:function(response,status,xhr){ //提交给use.php的数据成功后就执行的函数 $('#box').html(response); //获取提交给use.php成功的数据 }, timeout:3000, //如果3分钟还没能显示内容就必须停止运行ajax global:false, //将此ajax设置为局部,就不能接受其他全局功能了 error:function(xhr,errorText,errorType){ alert('错误'); // 找不到url就提示错误 alert(errorText+':'+errorType); alert(xhr.status+':'+xhr.statusText); } }); 适用于$.post的错误提示 $.post('use.php').error(function(xhr,errorText,errorType){ alert('错误'); // 找不到url就提示错误 alert(errorText+':'+errorType); alert(xhr.status+':'+xhr.statusText); }); error() $.post局部的方法 使用全局错误提示ajaxError(),只要是全局的$.ajax $.get $.post出现了错误 都会统一调用以下错误提示,如果是加上了global:false就不会调用其他全局事件 $(document).ajaxError(function(event,xhr,settings,infoError){ alert(xhr.status+':'+xhr.statusText); }); 以上是ajax执行失败后执行的方法,下面介绍ajax执行成功后执行的方法。 全局事件ajaxSend(),ajaxComplete(),ajaxSuccess(),ajaxError() $(document).ajaxSend(function(){ alert('正要但是还没触发ajax之前,执行这里'); }).ajaxComplete(function(){ alert('不管ajax执行成功还是失败ajax运行结束时,最后都执行这里'); }).ajaxSuccess(function(){ alert('ajax执行成功才执行这里'); }).ajaxError(function(){ alert(ajax执行失败才执行这里''); }); 请求成功后的局部事件写法 $.post没有局部的执行ajax前的触发事件 $('form input[type=button]').click(function(){ $.post('use.php',$('form').serialize()).success(function(){ }).complete(function(){ }).error(function(){ }); }); $.ajax({ type:'POST', //ajax选择POST方式提交数据 url:'use.php', //将数据提交到这个文件 data:$('form').serialize(), //获取到form中所有提交的数据 success:function(response,status,xhr){ //提交给use.php的数据成功后就执行的函数 $('#box').html(response); //获取提交给use.php成功的数据 }, timeout:3000, //如果3分钟还没能显示内容就必须停止运行ajax global:false, //将此ajax设置为局部,就不能接受其他全局功能了 error:function(xhr,errorText,errorType){ alert('错误'); // 找不到url就提示错误 alert(errorText+':'+errorType); alert(xhr.status+':'+xhr.statusText); }, complete:function(){ }, beforeSend:function(){ }, error:function(){ } });