Below I will bring you a brief analysis of how to use Ajax's beforeSend to improve user experience. Now share it with everyone and give it a reference
jQuery is an open source js framework that is often used. There is a beforeSend method in the $.ajax request, which is used to perform some actions before sending the request to the server. .
$.ajax({ beforeSend:function(){ // handle the beforeSend event }, complete:function(){ // handle the complete event } });
Prevent duplicate data
In actual project development, when submitting a form, it is often due to network or other reasons. When the user clicks the submit button, he mistakenly thinks that the operation is not successful, and then repeats the submit button operation times. If the front-end code of the page does not do some corresponding processing, it will usually result in multiple pieces of the same data being inserted into the database, resulting in an increase in dirty data. To avoid this phenomenon, disable the submit button in the beforeSend method in the $.ajax request, wait until the Ajax request is completed, and then restore the button's available state.
For example:
$.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); } });
Simulate Toast effect
ajax requests the server to load the data list When it prompts loading("Loading, please wait...")
$.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); } });
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. .
Related articles:
Quick solution to Ajax submission of garbled characters under IE
Ajax gets the data and then displays it on the page Implementation method
Ajax form asynchronous upload file example code
##
The above is the detailed content of A brief analysis on how to skillfully use Ajax's beforeSend to improve user experience. For more information, please follow other related articles on the PHP Chinese website!