使用Javascript / jQuery进行同步GET请求 [英] Synchronous GET request with Javascript/jQuery

查看:63
本文介绍了使用Javascript / jQuery进行同步GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以生成ajax GET请求,并根据返回的值设置一个全局JS变量。我使用这个变量(下面的代码中的isCalculateTax)进行进一步处理:

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;
 });
}

$(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();
 setCalculateTaxValue(taxStatementId);
 enumerateDocumentItems(isCalculateTax);
});

我的问题是,当调用enumerateDocumentItems()并执行isCalculateTax时,尚未从AJAX更新GET请求,因此我收到了不可预测的结果。

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.

如何在执行enumerateDocumentItems()之前等待必要的时间,以便isCalculateTax正确?

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

推荐答案

有两种方法可以做到这一点。首先,您可以更改 setCalculateTaxValue (并可能重命名),以便它接受在检索值时执行的回调。然后,您将传递 enumerateDocumentItems 作为回调。或者,这实际上违背了异步性的概念,您可以将其更改为使用 $ .ajax 并设置 aSync 选项为false。我推荐前者。

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.

这篇关于使用Javascript / jQuery进行同步GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆