如何通过ajax调用servlet来加载一个值,servlet返回到html tabel rowcell

时间:2014-01-07 11:21:10

标签: java jquery ajax jsp servlets

我是AJAX的新手,所以请帮帮我。

我的Ajax编码:

$(document).ready(function() {     
                alert("Hello trial");
                $('#weight').click(function(event) {  
                    alert("Hello click");
                 $.get('UpdateWeight',function(responseText) { 
                        alert("After the getJson");
                        $('#materialweigh').text(responseText);         
                        alert("Hello responsetext");
                    });
                });
            });

我的Jsp页面:

<body>
        <div>
            <table id="mytable" width="350px" border="1">
                <tr>
                    <td>S.No</td>
                    <td>Bag Weight</td>
                    <td id="materialweigh">Material Weight</td>
                </tr>
            </table>
        </div>
        <div>
            <button onclick="call_2();">OK</button>
            <input type="button" value="GetWeight" id="weight"/>
        </div>
    </body>

Servlet编码:

PrintWriter out = response.getWriter();
    System.out.println("Inside Get Method");
    try {
        servletweight = request.getParameter("weight");
        Pattern pattern = Pattern.compile("^\\d+\\.\\d{2}$");
        Matcher matcher = pattern.matcher(servletweight.trim());
        if (matcher.matches()) {
            request.setAttribute("Weight", servletweight.trim());
            System.out.println("Weight Captured::" + servletweight.trim());
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(servletweight);
        }
    } finally {
        out.close();
    }
  

Call_2功能:

function call_2(){

            var rows = document.getElementById("mytable").getElementsByTagName("tr").length;
            var total=rows+1
            $("#mytable").last().append("<tr><td>"+total+"</td><td></td><td></td></tr>");
        }

我想从servlet中获取权重以填充html表,这是一个连续的过程,因此需要ajax来处理而不加载整个页面。

1 个答案:

答案 0 :(得分:1)

在web.xml中,您应该指定servlet:

<servlet>
    <description></description>
    <display-name>ServletName</display-name>
    <servlet-name>ServletName</servlet-name>
    <servlet-class>com.example.package.ServletName</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletName</servlet-name>
    <url-pattern>/UpdateWeight</url-pattern>
  </servlet-mapping>

当单击按钮时,ajax请求将访问servlet。