开发者

Synchronous GET request with Javascript/jQuery

开发者 https://www.devze.com 2023-01-18 06:34 出处:网络
I have a function that makes ajax GET request and based on the value returned sets one global JS variable. I use this variable (isCalculateTax in the code below) for further processing:

I have a function that makes ajax GET request and based on the value returned sets one global JS variable. I use this variable (isCalculateTax in the code below) for further processing:

var isCalculateTax;

function setCalculateTaxValue(taxStatementId) {
 $.get('/taxstatements/calculatetax/' + taxStatementId, function (data) {
  isCalculateTax = data.isCalculateTax;
 });
}

$(docu开发者_开发技巧ment).ready(function () {
 // initially check the tax statements dropdown to see which one is selected
 // and set the isCalculateTax to the right value
 var taxStatementId = $('#taxStatements').val();
 setCalculateTaxValue(taxStatementId);
 enumerateDocumentItems(isCalculateTax);
});

My problem is that when enumerateDocumentItems() is called and executed the isCalculateTax is not yet updated from the AJAX GET request, so I receive unpredictable results.

How can I wait the necessary amount of time before executing enumerateDocumentItems() so that isCalculateTax will be correct?


There are two ways to do this. First, you could change setCalculateTaxValue (and probably rename it) so that it accepts a callback that gets executed when the value is retrieved. You'd then pass enumerateDocumentItems as the callback. Alternately, and this is really going against the concept of asynchronicity, you can change it to use $.ajax and set the aSync option to false. I recommend the former.

var isCalculateTax; // no longer needed?

function updateTaxValue(taxStatementId,callback) { 
 $.get('/taxstatements/calculatetax/' + taxStatementId, function (data) {
  isCalculateTax = data.isCalculateTax;
  if (callback) {
      callback.call( taxStatementId, data.isCalculateTax ); 
  }
 }); 
} 

$(document).ready(function () { 
 // initially check the tax statements dropdown to see which one is selected 
 // and set the isCalculateTax to the right value 
 var taxStatementId = $('#taxStatements').val(); 
 updateTaxValue(taxStatementId,enumerateDocumentItems); 
});

Using the callback makes it a little more flexible than simply referencing the callback function directly. It will allow you to reuse the update code for more than one purpose if necessary.


Just call enumerateDocumentItems() from inside the $.get callback function, right after isCalculateTax is set.

Just make sure the UI makes sense in between.

0

精彩评论

暂无评论...
验证码 换一张
取 消