Javascript / jQuery to Servlet communication

拟墨画扇 提交于 2019-12-23 06:16:25

问题


I was searching for this earlier and was little confused by the answer i got around so i felt like writing a complete code for this. This is for my future work and i hope someone get benefited by this.

Please see the answer below.


回答1:


This can be solve by both js and jquery. but since jquery is easier and shorter so, i am just going to write code for that. In this scenario i will make a ajax call on change of a selection in html / jsp page

Jsp page looks like this

<select class="target1">
   <option >Select type</option>
   <option >computer</option>
   <option >camera</option>
   <option >sound System</option>
   <option >battery</option>
</select>

<select class="target2">
    <option >Select type</option>
</select>

Here on selection from target1 i want to show another list in target2 selection. for this the jquery function is like following

$('.target1').change(function() {
    $.ajax({
        $('.target2').empty();
        url: 'http://localhost:8080/YourAppName/ServletName',
        data: {selectedValue: $(this).val()},
        success: function(response) {
            $('.target2').append(response);
        }
    });
});

Here I am pointing target1 and inside making an ajax call. Initially i am making the target2 selection empty. Then calling the servlet by the url and passing value using data. On success i am just appending the result in the target2 selection

in the ServletName (servlet) i write the following code:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        String selectedItem = request.getParameter("selectedValue");


        productList = connDB.getProduct(query);

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if(selectedItem == (Your Condition)){
                   out.println("<option >1</option>");
                   out.println("<option >2</option>");
                   out.println("<option >3</option>");
                   out.println("<option >4</option>");
            }else{}


        } finally {            
            out.close();
        }
    }

After executing this code you should get in the selection target2

1
2
3
4

As you can understand now you can customize it anyway you want.



来源:https://stackoverflow.com/questions/16067592/javascript-jquery-to-servlet-communication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!