[英]Update variable sent to ajax call with value from previous ajax response
[英]hold previous ajax response value into a jquery variable and add the value into next ajax response value
我有一個程序,可以在其中使用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);
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.