javascript:获取从ajax请求返回的值

时间:2018-06-12 13:54:01

标签: javascript jquery ajax

有一些用户字段,其中值传递给ajax请求。 用户字段以行的形式出现,每行用于根据指定的数量和其他选择生成金额。 在页面的某个位置,计算每行的总数,并将总成本保存在隐藏字段中。

挑战是在对数据库进行ajax调用后,将总的总成本作为变量返回。 很高兴能得到一些帮助。

function qmGetOrderTotalReview(){

    (function($){
        var order_total_cost = 0;
        var get_my_qty_cost = 0;
        for(var i = 1; i <= 10; i++){   

            var qm_product_id = '#product_id'+i;
            var qm_product_id_val   = $(qm_product_id).val();

            var qm_type_id = '#qm_type_id'+i;
            var qm_type_id_val  = $(qm_type_id).val();

            var qm_measure_id = '#qm_measure_id'+i;
            var qm_measure_id_val   = $(qm_measure_id).val();

            var qm_my_qty_id = '#my_qty_id'+i;
            var qm_my_qty_id_val    = $(qm_my_qty_id).val();

            get_my_qty_cost = qmGetMyQtyValueReview(i, qm_product_id_val, qm_type_id_val, qm_measure_id_val, qm_my_qty_id_val); 

            if(get_my_qty_cost > 0){            
                order_total_cost    = Number(order_total_cost) + Number(get_my_qty_cost); // add up total for each row to get grand total
            }       
        }//End loop through each row

        jQuery("#cm_total_cost").val(order_total_cost);  // append grand total to hidden field

    })(jQuery);

}//End function


function qmGetMyQtyValueReview(row_id, product_id, type_id, measure_id, my_qty){

    var my_qty_cost = 0;

    (function($){

        if(row_id && product_id && type_id && measure_id && my_qty){        

            var form_data = {
                product_id : product_id,
                type_id : type_id,
                measure_id : measure_id,
                my_qty : my_qty,
                secure_csrf_token_name : csrf
            }               

            $.ajax({
                url :   site_url+"/qm-get-product-qty-cost-review",
                type :  "POST",
                data :  form_data,
                dataType: "json",
                cache :     false
            })
            .done(function(resp){
                my_qty_cost = resp.value; // quantity cost for queried row
                raw_qty_cost = resp.raw_qty_cost;

                var qm_total_id = '#qm_total'+row_id;
                jQuery(qm_total_id).html('<div class="qty_total_okay qty_total_style">'+my_qty_cost+'</div>');

                var qm_my_qty_cost_id = '#qm_my_qty_cost'+row_id;
                jQuery(qm_my_qty_cost_id).val(raw_qty_cost);    
            })
            .fail(function(){       
                my_qty_cost = 0;
            });     
        }

    })(jQuery);

    return my_qty_cost; // return value to be used to calculate grand total    
}//End function

0 个答案:

没有答案