关于javascript基于DWR调用java函数的传值问题

$(function() {

            $("#sub").click(function(e) {

                var re = /^[1-9]+[0-9]*]*$/;//正整数正则表达式

                if ($("#count").val() == "" || !re.test($("#count").val())) {

                    $("#info").text("请输入合理数量").css("color", "#FF3333");

                    e.preventDefault();
                } else{
                
                 var productCount = 0;

                    // 获得产品库存
                    ProductService.getStockBalance($("#productId").val(),
                            function(data) {

                                productCount = data;                //productCount有值
                            });
                            
                            if(productCount < $("#count").val()) {            //productCount的值为空
                                  $("#info").text("已超出该产品的库存量").css("color", "#FF3333");

                    e.preventDefault();
                            }
                            
                     }
            });
        });

上面代码段中,productCount的通过后台函数获得返回值,但是这个值只会在后台函数快内有值,为了解决这个问题,应该将productCount定义为全局变量,才可以使productCount真正被赋值,代码如下:

$(function() {
    
    var productCount = 0;

                    // 获得产品库存
                    ProductService.getStockBalance($("#productId").val(),
                            function(data) {

                                productCount = data;
                            });

            $("#sub").click(function(e) {

                var re = /^[1-9]+[0-9]*]*$/;//正整数正则表达式

                if ($("#count").val() == "" || !re.test($("#count").val())) {

                    $("#info").text("请输入合理数量").css("color", "#FF3333");

                    e.preventDefault();
                } else if(productCount < $("#count").val()) {
                    $("#info").text("已超出该产品的库存量").css("color", "#FF3333");

                    e.preventDefault();
                }
            });
        });


你可能感兴趣的:(JavaScript,jquery,DWR)