我有一个程序,我可以使用ajax获取价格值,并且我希望下次获取价格值时,之前的价格值可以添加到当前价格值中。
但问题是,当我获得当前价格并且获得下一个价格值后,之前的价格无法保留,它可以被下一个值覆盖,并且我无法添加这些值
解决办法是什么,请帮帮我
在 JQUERY 中
$(document).on('change','.searchAmount',function()
{
var id=$(this).attr("id");
var amount=$('#'+id).val();
var rate=$('#rate'+idd).val();
var cgst=$('#cgstrate'+idd).val();
var sgst=$('#sgstrate'+idd).val();
$.ajax({
url:"SellSameStateAmountChange.jsp",
method:"post",
dataType:'json',
data:{amount:amount,rate:rate,cgst:cgst,sgst:sgst,qty:qty},
cache:false,
success:function(data)
{
var sum=0.0;
$('#rate'+idd).val(data.price);
sum+=data.amount;
alert(sum);//Like this
}
});
});
在 JSP 中
<%--
Document : SellSameStateAmountChange
Created on : Feb 12, 2018, 8:10:43 PM
Author : Lenovo
--%>
<%@page import="org.json.JSONObject"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page language="java" %>
<%@page import="java.sql.*" %>
<%@page import="java.util.*" %>
<%
double amount=Double.parseDouble(request.getParameter("amount"));
double rate=Double.parseDouble(request.getParameter("rate"));
double cgst=Double.parseDouble(request.getParameter("cgst"));
double sgst=Double.parseDouble(request.getParameter("sgst"));
double qty=Double.parseDouble(request.getParameter("qty"));
double gst=cgst+sgst;
double changedRate=rate*qty;
double price=amount-(gst/100)*changedRate;
JSONObject json=new JSONObject();
json.put("price",price);
json.put("amount",amount);
out.print(json.toString());
%>
最佳答案
将 var sum=0.0
移到 ajax 回调之外并更改事件,这样它就不会每次都“重置”。
// Moved to here
var sum=0.0;
$(document).on('change','.searchAmount',function()
{
var id=$(this).attr("id");
var amount=$('#'+id).val();
var rate=$('#rate'+idd).val();
var cgst=$('#cgstrate'+idd).val();
var sgst=$('#sgstrate'+idd).val();
$.ajax({
url:"SellSameStateAmountChange.jsp",
method:"post",
dataType:'json',
data:{amount:amount,rate:rate,cgst:cgst,sgst:sgst,qty:qty},
cache:false,
success:function(data)
{
// removed from here
$('#rate'+idd).val(data.price);
sum+=data.amount;
alert(sum);//Like this
}
});
});
请注意,这会生成一个通常不受欢迎的“全局变量”,因此有一些方法可以解决此问题,例如使用命名空间或将总和直接存储在元素上。
例如:
// Moved to here
var sum=0.0;
$(document).on('change','.searchAmount',function()
{
// setup variables skipped for brevity
$.ajax({
url:"SellSameStateAmountChange.jsp",
method:"post",
dataType:'json',
data:{amount:amount,rate:rate,cgst:cgst,sgst:sgst,qty:qty},
cache:false,
success:function(data)
{
$('#rate'+idd).val(data.price);
var sum = $(this).data("sum")
sum+=data.amount;
$(this).data("sum", sum);
alert(sum);
}
});
});
关于javascript - 将先前的ajax响应值保存到jquery变量中并将该值添加到下一个ajax响应值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48763121/