Reputation: 14877
I am newbie to jqGrid
, and populating data from Servlet via Ajax
call and displaying in jqGrid
. This works fine no problem. But, In my case column names are dynamic, as I am showing dates as column names.
So, I found below code when searching for Dynamic colModel
for jqGRid
.
But, This causes two Ajax call. Has anyone worked with dynamic column headers ?
<script type="text/javascript">
var grid = $("#rowsList");
var url = '/getRowList?Id=9371&fromDate=2011-12-06&toDate=2012-12-06';
jQuery().ready(function (){
$.ajax({
url: url,
dataType: 'json',
success: function(response) {
prepareGrid(response);
},
error: function(request, textStatus, errorThrown) {
alert(textStatus + " : " + request.responseText);
}
});
});
function prepareGrid(response){
if (response) {
if (!response.Error) {
var colData = getColumnsData(response.columnData);
colData = eval('{' + colData + '}');
grid.jqGrid({ // This makes second server call
url: url,
datatype: 'json',
mtype: 'POST',
colModel: colData,
colNames: response.columnData,
height : 'auto',
pager: '#pager',
viewrecords: true,
loadtext: 'Loading',
sortorder: "asc",
gridview: true,
altRows: true,
cellEdit: false,
caption: 'Data List'
});
}
}
}
/**
* Creates column data for jqgrid
*/
function getColumnsData(Data) {
// return column data array in jqGrid compatible format
// This works fine
}
</script>
My other choice to return only column names in the first call and set colModels
but It would be better if it can be done in single server call.
Upvotes: 3
Views: 1678
Reputation: 221997
I want to warn you with reducing of the number of Ajax calls. If you are newbie in jqGrid it's important to understand some common thing in the usage of jqGrid:
grid.jqGrid({...});
.url
will be used multiple times by jqGrid.The grid has some common user interface elements in pager (see the answer)
which can be used by user to interact with jqGrid. So if the user click on the "Next Page" button, Change the number of displayed rows or change the sorting column (or the direction of sorting) new request to the server, to url
will be send. It is very practical to use other elements of user interface like searching tool:
which also produce new request to url
with modified parameters. After receiving the server response only the grid body will be replaced. The other parts of the grid will stay unchanged. You can use GridUnload
method to recreate the whole grid (see here examples)
So if you would transfer column definition every time together with the data of the grid you will send unneeded data, which can reduce the performance instead of improving which you want.
Upvotes: 2