gpt4 book ai didi

javascript - jQuery 中变量的 riptscope

转载 作者:行者123 更新时间:2023-12-03 11:20:24 24 4
gpt4 key购买 nike

我有以下 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com