gpt4 book ai didi

javascript - 快速并发的 ajax 调用

转载 作者:行者123 更新时间:2023-11-27 22:40:42 25 4
gpt4 key购买 nike

我目前正在使用 Laravel 为 POS 添加销售。这里我们可以使用条形码来扫描产品代码,当输入条形码时,它会调用检查函数,如果在购物车表中找到相同的产品代码,则它只是将数量值加1,否则它会进行ajax调用,该调用将返回该特定产品的详细信息。我的 jQuery 函数如下所示:

 function check() {
if ($(".product_code").length) {
var product_code = $("#product_code").val();
var total = $('#cart_contents tr').length;
$('#cart_contents tr').each(function(index) {
var p_code = $(this).find(".product_code").val();
if (product_code == p_code) {
var num = +$(this).find('.product_quantity').val() + 1;
$(this).find('.product_discount').val(0);
$(this).find('.product_quantity').val(num).keyup();
return false;
} else if (index === total - 1) {
populatecart();
}
});
} else {
populatecart();
$(".cart_content_area").hide();
}
}

function populatecart() {
var product_code = $("#product_code").val();
$.ajax({
url: "{{ url('getproductdata')}}",
data: {
p_id: product_code
},
datatype: "JSON",
type: "get",
success: function(data) {
if (data == 'null') {
alert('No product code found!');
} else {
$.each(data, function(k, v) {
$("#cart_contents").append('<tr>' +
'<td class="quantity"> {!! Form::text('sales_quantity[]', 1, ['class'=>'product_quantity form-control']) !!} </td>' +
'<td class="product_codes"><input type="text" name="product_code[]" value="' + v["product_code"] + '" class="form-control product_code" readonly/></td>' +
'<td><input type="text" name="product_name[]" value="' + v["product_name"] + '" class="form-control product_name" readonly/> </td>' +
'<td><input type="text" name="unit_value[]" value="' + v["sell_price"] + '" class="form-control unit_value" readonly/></td>' +
'<td>{!! Form::text('product_discount[]', 0, ['class'=>'product_discount form-control']) !!}</td>' +
'<td><input type="text" name="line_total[]" value="' + v["sell_price"] + '" class="form-control line_total" readonly/></td>' +
'<td class="remove_row"><input name="product_id[]" type="hidden" value="' + v["id"] + '" /><button type="button" class="removebutton" title="Remove this row">X</button></td>' +
'</tr>');
calculateTotalSum();
});
}
}
});
}

但是,这里的问题是,当我尝试同时扫描相同的产品(即具有相同产品代码的产品)时,它会增加数量,但如果我很快尝试相同的操作,相同的产品就会填充到两个不同的产品中购物车表的行,但我真正想要的是让产品的数量值为 2,而不是为相同的产品代码创建 2 行。

我该如何处理这个问题?

最佳答案

而不是使用基于回调的 API。我建议你使用基于 promise 的。流程是这样的。

var cart = {};
if(cart[product_code] == undefined)
{
cart[product_code] = $.ajax(url: "{{ url('getproductdata')}}" ,
data:{
p_id:product_code
},
datatype:"JSON",
type: "get");
cart[product_code].done(function(data){
//do the initialization
});
}
else
{
cart[product_code].done(function(){
//do the update.
});
}

关于javascript - 快速并发的 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38764262/

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