通过json从服务器端返回sum

returning sum from server side by json

本文关键字:返回 sum 服务器端 json 通过      更新时间:2023-09-26

我通过onkey-up事件添加两个文本框值。每次输入数据时,都会将数据提交给服务器,然后通过json返回结果。我通过json(通过组合的onchange事件)获得了一个文本框,而html中已经存在另一个文本盒,当我在第二个文本框(以html)中更改数据时,会计算合计,但当我在第一个文本框中更改数据(以javascript)时,不会计算合计?我哪里错了?第一个和第二个文本框具有相同的类子名称

 $(document).ready(function() {
$(".submitme").keyup(function () {
        $.getJSON('total.jsp', {
        firsttextboxname: jQuery("#firsttextbox").val(), secondtextboxname:
 jQuery("#secondtextbox").val()
        }, function (responseData) {
             var total = responseData.sum;
              $("#thirdtextbox").val(total);// displays total
    });
});

 $("#combo").change(function () {
        $.getJSON('combo.jsp', {
            comboboxname: this.value
        }, function (responseData) {
           // returns a text box (first text box)
     $("#adiv").empty().append("<input type='text' class='submitme' id='firsttextbox' name='firsttextboxname'/>");
    });
 });
});

html

<div id="adiv">
// getting first text box here
</div>
//second text box whose data is also taken along with first text box each time
 <input type="text" id="secondtextbox" class="submitme" name="secondtextboxname"/>// taking value from this text box to calculate sum
 <input type="text" id="thirdtextbox"/>// auto filling sum here

服务器端(total.jsp)

 String a=request.getParameter("firsttextboxname");// getting first text box name
 String b=request.getParameter("secondtextboxname");/ getting second text box name
 int c=Integer.parseInt(a);// converting to integer
 int d=Integer.parseInt(b);//converting to integer
 int e=c+d;// calculating total
 JSONObject jsonObj= new JSONObject(); 
 jsonObj.put("sum",e);// sending sum to client side
 response.setContentType("application/json");
 response.getWriter().write(jsonObj.toString());

异步添加组合框(或任何元素)时,它不会获得keyup事件绑定。你必须像这样使用.live():

$(".submitme").live("keyup", function() {
    // stuff
});

有关.live()如何工作的详细信息,请参阅jQuery文档。

在我看来,您将keyup事件添加到domready中的".submitme"类元素中,但第一个文本框还没有出现在文档中。

它添加在你的#组合的更改事件上,所以它不会得到分配给它的keyup事件。