sairn
sairn

Reputation: 490

Why does this *jquery.dataTables.js* example not work?

Why is this DataTables.js example failing?

Its a simple enough example, and the code seems to be correct.
-But, it fails with an exception... (see below)

(What is wrong with the code?... -Or, what else can I look at to determine and fix the issue?)

Thank you for any help.

Further information is below...

Here is the HTML...

    <form id="page0Form">
        <table class="table table-striped table-hover" id="myGrid"></table>    
    </form>     

Here is the javascript that sets up the datatable...

    var jq = jQuery.noConflict();

    jq(document).ready(function () 
    {
        jq('#myGrid').dataTable({
            "ajax": "page0/tableData",
            "columns": [
                {"data": "testvala"},
                {"data": "testvalb"},
                {"data": "testvalc"}
            ]
        });
    });

Here is the JSON string returned by the AJAX call...

    {"data":[{"testvala":"valuea0","testvalb":"valueb0","testvalc":"valuec0"},{"testvala":"valuea1","testvalb":"valueb1","testvalc":"valuec1"},{"testvala":"valuea2","testvalb":"valueb2","testvalc":"valuec2"}]}

Here is the java class that contains the method returning the JSON string...

    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.io.IOException;
    import javax.servlet.http.HttpSession;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.apache.log4j.Logger;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.HashMap;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;

    @Controller
    @RequestMapping("/page0")
    @Scope("session")
    public class Page0Controller implements Serializable
    {
        private static final Logger LOG = Logger.getLogger("Page0Controller");
        private static final long serialVersionUID = 5024226983105965553L;

        //...........................................................    
        //...........................................................
        //...NOTE: this is the method that returns the JSON string...
        //...........................................................    
        //...........................................................    
        @RequestMapping(value = {"/tableData"}, method = RequestMethod.GET)    
        @ResponseBody    
        public String tableData(HttpServletRequest request, HttpSession session)
        {
            LOG.info("______________________tabledata______________________entering...");

            String testbeanlistjson = "";        
            ArrayList<TestBean> testBeanList = new ArrayList<TestBean>();        
            for (int i=0; i<3; i++)
            {
                testBeanList.add(new TestBean(
                    "valuea" + i,
                    "valueb" + i,
                    "valuec" + i
                ));
            }

            try
            {
                HashMap<String, ArrayList<TestBean>> data = new HashMap<>();                
                data.put("data", testBeanList);    
                ObjectMapper mapper = new ObjectMapper();          
                testbeanlistjson = mapper.writeValueAsString(data); //(testBeanList);  //(data); //(testBeanList);
                session.setAttribute("testbeanlistjson", testbeanlistjson);
            }
            catch (IOException e)
            {
                LOG.error("______________________tabledata______________________Exception - e.getMessage()=" + e.getMessage(), e);
            }

            LOG.info("______________________tabledata______________________testbeanlistjson=" + String.valueOf(testbeanlistjson));
            //Gson gson = new Gson();
            //testbeanlistjson = gson.toJson(testBeanList);

            return testbeanlistjson;
        }        

        @RequestMapping(value = "", method = RequestMethod.GET)
        public ModelAndView page0(ModelMap model, HttpSession session)
        {
            LOG.info("____________________page0___________________entering...");
            return new ModelAndView("page0");
        }    
    }

Here's the screen output...

enter image description here

Here is the exception that occurs...

enter image description here

Here is the jquery.dataTables.js method where the javascript exception occurs...

    -
    -
    -
    /**
     * Draw the table for the first time, adding all required features
     *  @param {object} settings dataTables settings object
     *  @memberof DataTable#oApi
     */
    function _fnInitialise ( settings )
    {
        var i, iLen, iAjaxStart=settings.iInitDisplayStart;
        var columns = settings.aoColumns, column;
        var features = settings.oFeatures;

        /* Ensure that the table data is fully initialised */
        if ( ! settings.bInitialised ) {
            setTimeout( function(){ _fnInitialise( settings ); }, 200 );
            return;
        }

        /* Show the display HTML options */
        _fnAddOptionsHtml( settings );

        /* Build and draw the header / footer for the table */
        _fnBuildHead( settings );
        _fnDrawHead( settings, settings.aoHeader );
        _fnDrawHead( settings, settings.aoFooter );

        /* Okay to show that something is going on now */
        _fnProcessingDisplay( settings, true );

        /* Calculate sizes for columns */
        if ( features.bAutoWidth ) {
            _fnCalculateColumnWidths( settings );
        }

        for ( i=0, iLen=columns.length ; i<iLen ; i++ ) {
            column = columns[i];

            if ( column.sWidth ) {
                column.nTh.style.width = _fnStringToCss( column.sWidth );
            }
        }

        // If there is default sorting required - let's do it. The sort function
        // will do the drawing for us. Otherwise we draw the table regardless of the
        // Ajax source - this allows the table to look initialised for Ajax sourcing
        // data (show 'loading' message possibly)
        _fnReDraw( settings );

        // Server-side processing init complete is done by _fnAjaxUpdateDraw
        var dataSrc = _fnDataSource( settings );
        if ( dataSrc != 'ssp' ) {
            // if there is an ajax source load the data
            if ( dataSrc == 'ajax' ) {
                _fnBuildAjax( settings, [], function(json) {
                    var aData = _fnAjaxDataSrc( settings, json );

                    // Got the data - add it to the table
                    for ( i=0 ; i<aData.length ; i++ ) {
                        _fnAddData( settings, aData[i] );
                    }

                    // Reset the init display for cookie saving. We've already done
                    // a filter, and therefore cleared it before. So we need to make
                    // it appear 'fresh'
                    settings.iInitDisplayStart = iAjaxStart;

                    _fnReDraw( settings );

                    _fnProcessingDisplay( settings, false );
                    _fnInitComplete( settings, json );
                }, settings );
            }
            else {
                _fnProcessingDisplay( settings, false );
                _fnInitComplete( settings );
            }
        }
    }

    -
    -
    -

javascript libraries, etc...:

Bootstrap v3.3.2

DataTables v1.10.5 (org.webjars)

jackson-core v2.3.4 (com.fasterxml.jackson.core)

Jackson-databind v2.3.4 (com.fasterxml.jackson.core)

Spring MVC v3.2.8

Upvotes: 0

Views: 577

Answers (1)

davioooh
davioooh

Reputation: 24666

@ResponseBody annotation automatically provides serialization for return object of a controller method, but you are also using an ObjectMapper to serialize your aData, so the problem could depend on this.

When I implemented server-side pagination for DataTables plugin I was returning an object mapping aData. I created a simple library to achieve this: https://bitbucket.org/davioooh/datatablepager

Take a look to source code. It could be helpful.

Upvotes: 1

Related Questions