This is often the case when implementing data interaction with the background:
1. Need to use an AJAX request background data, and to get the data and then render to the page, this time must be synchronized (Async:false).
2. However, there will be another situation at this time when the AJAX request takes a long time to loading a layer to show the waiting state
3. The beforesend is ineffective at this time, even if the loading code is not written in Ajax.
4. The reason is that the Ajax async set to False when the browser's rendering (UI) thread and JS thread are mutually exclusive, in the execution of JS time-consuming operation, page rendering will be blocked off. There is no problem when we execute asynchronous Ajax, but when set to sync request, the other actions (the code behind the AJAX function, and the render thread) will stop. Even if my DOM action statement is in the previous sentence of the request, the synchronization request will "quickly" block the UI thread and give it no time to execute. That's why the code is failing.
5. Solution using jquery $. Deferred () and $.when (). Done () to achieve the effect of synchronous execution asynchronously (note: implemented asynchronously): as shown in
function Getajaxdata () {var defer = $. Deferred (); $. Ajax ({URL: ', type: ' Post ', data: ', Async:true, DataType: ' JSON ', success:function (data) {defer. R Esolve (data); } }); return defer; //Execute $ (' #id '). Click (function () {showloading ();//Show wait icon $. When (Getajaxdata ()). Done (function (data) {CLO Seloading (); Hide wait icon console. log (data); Execute other code}); });
RELATED links:
Http://www.cnblogs.com/lvdabao/p/3744030.html
Http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html