作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下 AJAX。
我需要做的是使用变量 tax_rate
$.ajax
之外称呼。我的 ajax 调用工作正常,因为变量 tax_rate
在[1]中显示正确的值,但该变量在[2]中变得无用。
我在变量作用域上做错了什么吗?
<script>
jQuery(document).ready(function($) {
$(document).on('blur','#form',function() {
var subsum = 0;
var tax_rate = 0;
var tax_amount = 0;
$('.form-row').each(function() {
// calculate sums and totals per each form-row
subsum = Number( $(this).find('.unit').val() * $(this).find('.price').val() ).toFixed(2);
$(this).find('.subsum').empty().val(subsum);
// calculate tax amount
var tax_id= $(this).find('.tax_code').val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// call ajax to retrieve the tax rate
$.ajax({
url: ajaxurl,
data:' action=get_tax_rate_by_id&tax_id='+tax_id,
type:'GET',
success:function(results) {
tax_rate = results;
alert( tax_rate ); // [1] Obviously, this one properly alerts tax rate.
}
});
alert( tax_rate ); // [2] This one always alerts 0.
});
});
});
最佳答案
您必须同步进行 ajax 调用,因为当 JavaScript 异步运行时,警报将在完成 ajax 请求之前执行。虽然它会让你的代码有点慢,但你将能够在ajax之外返回tax_rate。您可以使用
async:false
在你的 ajax 选项中执行此操作。
关于javascript - jQuery 中变量的 riptscope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27143404/
这个问题已经有答案了: How do I return the response from an asynchronous call? (42 个回答) 已关闭 8 年前。 我有以下 AJAX。 我需
我是一名优秀的程序员,十分优秀!