Loading alternative content via tabs and jQuery and JSP

前端 未结 1 706
面向向阳花
面向向阳花 2020-12-12 04:51

I have a table of data for a policy type (options are Single, Couple, Family & Single Parent Family). I want to have a tabbed interface with each policy type occupying

相关标签:
1条回答
  • 2020-12-12 05:46

    Have you considered the JSON format? There are Java API's to seamlessly convert a (collection or map of) Javabean object(s) into JSON format, such as Google Gson. In JavaScript/jQuery you can handle JSON perfectly as if it's a worthfully JavaScript object. It is comparable with a Javabean in Java. No overheads like with formatting and parsing XML's.

    You can create a Servlet which writes a JSON string to the response so that it can be called by jQuery's $.getJSON(). Here's a kickoff example where Item is a fictive Javabean with three properties id, name and value:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Item> items = itemDAO.list();
        String json = new Gson().toJson(items);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
    

    To display those items in a table, just do roughly like this in jQuery:

    <script>
        $(document).ready(function() {
            $.getJSON('json/items', function(items) {
                $(items).each(function(i, item) {
                    var row = $('#table').append('<tr>');
                    row.append('<td>').text(item.id);
                    row.append('<td>').text(item.name);
                    row.append('<td>').text(item.value);
                });
            });
        });
    </script>
    
    ...
    
    <table id="table"></table>
    

    That's all! Hope this gives new insights. You can use this in the click event of any tab. You could even reuse the same table for display if that doesn't differ that much. Just do a $('#table').empty() beforehand to get rid of all rows.

    Edit: I overlooked one important consideration:

    but i wasn't sure about accessibility - would screen readers pick up this data?

    Screenreaders won't execute any JavaScript/CSS. If this is actually a showstopper, then you'll need to drop the JS/jQuery idea and go for "plain vanilla" synchronous requests with normal <a> links in each tab and take benefit of Servlet and JSP's JSTL/EL powers to display content conditionally based on the request parameters.

    0 讨论(0)
提交回复
热议问题