jquery是经常使用的一个开源js框架,其中的$.ajax请求中有一个beforesend方法,用于在向服务器发送请求前执行一些动作。
$.ajax({ beforesend:function(){ // handle the beforesend event }, complete:function(){ // handle the complete event } });
防止重复数据
在实际项目开发中,提交表单时常常由于网络或者其原因,用户点击提交按钮误认为自己没有操作成功,进而会重复提交按钮操作次数,如果页面前端代码没有做一些相应的处理,通常会导致多条同样的数据插入数据库,导致脏数据的增加。要避免这种现象,在$.ajax请求中的beforesend方法中把提交按钮禁用掉,等到ajax请求执行完毕,在恢复按钮的可用状态。
举个例子:
$.ajax({ type:"post", data:studentinfo, contenttype:"application/json", url:"/home/submit", beforesend:function(){ //禁用按钮防止重复提交 $("#submit).attr({disabled:"disabled"}); }, success:function(data){ if(data=="success"){ // 清空输入框 clearbox(); } }, complete:function(){ $("#submit").removeattr("disabled"); }, error:function(data){ consloe.info("error:"+data.responsetext); } });
模拟toast效果
ajax请求服务器加载数据列表时提示loading(“加载中,请稍后...”)
$.ajax({ type:"post", contenttype:"application/json", url:"/home/getlist", beforesend: function(){ $("loading").show(); }, success: function(data){ if (data=="success"){ // ... } }, error: function(){ console.info("error:"+data.responsetext); } });
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
ie下ajax提交乱码的快速解决方法
ajax获取数据然后显示在页面的实现方法
ajax表单异步上传文件实例代码
以上就是浅析巧用ajax的beforesend提高用户体验的详细内容。
