繁体   English   中英

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

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

我是刚使用json和ajax的人。 请有人帮助我如何将值附加到选项标签。 值将被打印在页面本身上,而不是选项标签内。 我看过很多例子,但看不懂。

检索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();
    }   
}

我的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>

这段代码可以正常工作并添加到下拉列表中,但这些值也会显示在页面顶部。有人可以给我解决方案吗?

    <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