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

时间:2017-06-08 12:08:59

标签: java arrays jsp

我是新手使用json和ajax。请有人帮我介绍如何将值附加到选项标签。这些值将打印在页面本身而不是选项标签内。我见过很多例子,但不明白。

Retrieveservlet:

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>

1 个答案:

答案 0 :(得分:0)

此代码在下拉列表中起作用并附加,但值也会显示在页面顶部。有人可以为我提供解决方案吗?

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