This time I will bring you the difference between using Ajax to achieve synchronization and asynchronous implementation, and what are the precautions for using Ajax to achieve synchronization and asynchronous implementation. The following is a practical case, let's take a look.
When sending and receiving data to the background through ajax, synchronization and asynchronous problems often occur. Since ajax is loaded asynchronously by default, but sometimes synchronization or synchronization effects are needed, there are the following two solutions.
Option 1: Execute certain methods in the callback function, that is, wait until successful return from the background before executing.
Example:
$.getJSON("/data-access/sens-config/IPandPortSel",{},function(resp){ if(resp.code==0){ $.each(resp.data,function(i,obj){ option_net_type += addOption(obj); }); $("#edit-addr_id").append(option_net_type); addr_idOld = $('#edit-addr_id').val(addr_id); } });
The red part must be executed after the data is returned successfully. If it is placed outside if(resp.code==0){} ((but Put it after $.getJSON();) there will be a red part of the code that has been executed before the data is returned from the background.
Method 2: Use the standard ajax delivery method##. #
$.ajax({ type : "post", url : "/data-access/manufacturer/deleteBranch", data : data, async : false,//取消异步 success : function(resp){ if(resp.code==0){ if(ids.length>=currentListNum&¤tPage!=1){ currentPage = currentPage - 1; } var para = { mypara :currentPage, startPage : currentPage, }; $('p.page-box').data('myPage').setOptions({data: para}); } } });
Note: This method is only a local synchronous transmission method and will not affect other transmissions. It is relatively safeAnd recommended one
There is another way:
// $.ajaxSettings.async = false; // $.getJSON("/data-access/ip-config/deleteBranch",data,function(resp){ // if(resp.code==0){ // if(ids.length>=currentListNum&¤tPage!=1){ // currentPage = currentPage - 1; // } // var para = { // mypara :currentPage, // startPage : currentPage, // }; // $('p.page-box').data('myPage').setOptions({data: para}); // } // }); // $.ajaxSettings.async = true;
Recommended reading:
Use Blod to make ajax progress bar downloadHow does Ajax realize city secondary linkageThe above is the detailed content of What is the difference between synchronous and asynchronous implementation using Ajax?. For more information, please follow other related articles on the PHP Chinese website!