简体   繁体   English

如何使用json从servlet到jsp检索值

[英]how to retrieve the values from servlet to jsp using json

I'm new to use json and ajax. 我是刚使用json和ajax的人。 Please someone help me on how to append the values to the option tag. 请有人帮助我如何将值附加到选项标签。 The values are getting printed on the page itself than inside the option tag. 值将被打印在页面本身上,而不是选项标签内。 I have seen so many examples but do not understand. 我看过很多例子,但看不懂。

Retrieveservlet : 检索servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   // TODO Auto-generated method stub

   System.out.println("action is called inside dropdown");
   ViewValuesInDB daoobj = new ViewValuesInDB();
   ArrayList<String> list = new ArrayList<String>();
   String json = null;
   try {
       list = daoobj.makeConnection();
       System.out.println(list);
       if(null == list){
           System.out.println("list is null");
       }
       else{
           System.out.println("list has values");
       }
       System.out.println("size of ids list :"+list.size());        

       /*using json*/
       json = new Gson().toJson(list);
       System.out.println(json);

       response.setContentType("application/json");
       response.getWriter().write(json);

    }catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

my jsp code : 我的jsp代码:

<script>
    $(document).ready(function() {
        $.get("Retrieveservlet", function(responseJson) {   
            ('#dropDownId').append($('<option>').text(value)('value'));
        });
    });
</script>
<body>
    <label for="dropDownId">Country*:</label>
    <select id="dropDownId">
    </select>
</body>

This code works and appending in the dropdown but the values are getting displayed at the top of the page too.Can someone give me solution for this? 这段代码可以正常工作并添加到下拉列表中,但这些值也会显示在页面顶部。有人可以给我解决方案吗?

    <script>
        $(document).ready(function() {
            $.get("Retrieveservlet", function(json) {
                /*  x = json[0];
                 alert(x); */
                var myselect = $('#dropDownId');
                $.each(json, function(index, key) {
                    myselect.append($('<option></option>').val(key).html(key));
                });
                //$('#dropDownId').append(myselect.html());
            });
        });
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM