问题描述:

There are accordion panels, each panel has its own variables in javascript.

I want to save data from each panel in jQuery using something like transaction or queue of POST requests.

Every panel binds its own event to onSave click by preparing the data.

//panel1 that prepares the data

$("#save").click(function() {

globalvar['panel1'] = 'somedata';

});

//panel2 prepares the data

$("#save").click(function() {

globalvar['panel2'] = 2*21+11;

});

How can I make AJAX request, after all panels has been prepared their data?

网友答案:

You can do it like this: Suppose your panel's data aren't loaded onLoad, add a class to each panel. This class means that data hasn't been loaded yet for specific panel

<div class="noDataLoaded"></div>

Remove that class when data is loaded

$("#save").click(function() {
  //code to load data
  //Adjust according to your HTML structure 
  $(this).removeClass("noDataLoaded"); //encapsulate this when it has succeeded loading. 
  groupPost();
});

Function that checks if all data has been loaded

   function groupPost() {
     if($(".noDataLoaded").length == 0){
       $.ajax({
        //code
       });
      }
    }

groupPost() will only fire if there are no elements that's using noDataLoaded class and that only happens if you click all the panels and loaded its data.

网友答案:
var dataToPost = new Array();
var isButton1Clicked = false;
var isButton2Clicked = false;

//panel1
$("#save").click(function() {
  isButton1Clicked = true;
  dataToPost['panel'] = btoa($('#blob1').val());
  checkAndSubmit();
});
//panel2
$("#save").click(function() {
  isButton2Clicked = true;
  dataToPost['panel2_amount'] = $('#multi').val() * $('#multi2').val() + 1;
  dataToPost['crc32'] = crc32($('#blob2').val());
  checkToSubmit();
});


//some magic function
function checkToSubmit() {
 //make only ONE ajax request, saving data from all panels
 if (isButton1Clicked && isButton2Clicked) {
   $.ajax({
     type: 'POST'
     data: dataToPost
   });
 }
}
相关阅读:
Top