我有一个包含3个元素(Qty,UnitCost和TotalPrice)的表单,这些表单是根据表单中较早的其他数据的结果计算出来的。
Qty和UnitCost正在基于jquery Get正确填写,但是我只使用普通旧javascript的总价格不会更新,除非我在早期字段中进行更改(之后它确实正确更新)。
我仍然对jquery很新,并且在我去的时候自学,所以我可能会遗漏一些东西。
表格看起来像这样
A(文字),B(下拉),C(下拉),数量,单位成本,TotalPrice
//Get the unit cost
$.get("calcCost.php", {item:item}, function(data) {
document.getElementById(unitCostField).value = data;
});
unitCost = document.getElementById(unitCostFiled).value;
Qty的代码基本相同 - 只是字段和php脚本被警告。两者都正常工作。
但是,当我尝试计算TotalPrice(只是Qty * UnitCost)时,它不会立即更新。它从0开始 - 当数量或单位成本尚未填补时,这是预期的。
//Total Cost
cost = unitCost * qty
document.getElementById(costField).value = cost;
(document.getElementById中的变量已在别处定义);
有什么想法吗?
答案 0 :(得分:1)
您需要记住,AJAX中的A代表异步,这意味着您无法立即使用AJAX请求的结果。相反,浏览器将执行请求,完成调用堆栈中的所有其他操作,然后,只要那时您的请求返回响应,您的ajax成功是否会执行。
您提供的示例更有趣,因为您的成本计算例程需要在 Qty和UnitCost请求完成后运行,并且只有在两者都成功时才运行。我认为像这样的问题的最佳解决方案,特别是你已经在使用jquery,是Deferred对象。
$ .when的jquery docs(这是您可能要考虑使用的方法)显示与您的问题几乎完全相同的问题的解决方案。 但是,为了方便起见(为简洁起见省略了错误处理程序):
var calcCostReq = $.get("calcCost.php", {item:item}).done(function(data) {
document.getElementById(unitCostField).value = data;
unitCost = document.getElementById(unitCostFiled).value;
});
var qtyReq = $.get("qty.php").done(function(data) {
//whatever you need to do when qty was successful
});
$.when(calcCostReq, qtyReq).done(function() {
cost = unitCost * qty
document.getElementById(costField).value = cost;
}
答案 1 :(得分:0)
在AJAX请求填充之前,您正在检索unitCostField
值。即使unitCost
赋值低于$.get
方法,它仍将在AJAX请求完成之前执行。
依赖于AJAX请求的代码必须在回调函数内处理。
var qty;
function calcCost() {
var unitCost = document.getElementById(unitCostField).value,
cost = unitCost * qty;
document.getElementById(costField).value = cost;
}
$.get("calcCost.php", {item:item}, function(data) {
document.getElementById(unitCostField).value = data;
calcCost();
});