La mia soluzione è la stessa idea dell'eccellente risposta di Teoman Shipahi da agosto 2015.
Ho un servizio Web che restituisce un set di dati JSON, ma le colonne effettive potrebbero variare nel tempo.
Quello che volevo fare era nascondere alcune delle colonne JSON nel mio jqGrid, e impostare la larghezza di alcune delle colonne in base se questo particolare settore JSON è stato uno dei settori più importanti (in questo caso, SegmentName
).
Ecco cosa mi è venuta:
$(function() {
// Load the JSON data we'll need to populate our jqGrid
// ID of a [Segment_Set] record in our database (which our web service will load the data for.
var SegmentSetId = 12345;
$.ajax(
{
type: "GET",
url: "/Service1.svc/LoadSegmentAttributes/" + SegmentSetId,
dataType: "json",
success: function (JSONdata) {
//
// Work through our JSON data, and create the two arrays needed by jqGrid
// to display this dynamic data.
//
var listOfColumnModels = [];
var listOfColumnNames = [];
for (var prop in JSONdata[0]) {
if (JSONdata[0].hasOwnProperty(prop)) {
// We have found one property (field) in our JSON data.
// Add a column to the list of Columns which we want our jqGrid to display
listOfColumnNames.push(prop);
// How do we want this field to be displayed in our jqGrid ?
var bHidden = (prop == "SegmentID") || (prop == "SegmentSequenceInx");
var columnWidth = (prop == "SegmentName") ? 200 : 50;
listOfColumnModels.push({
name: prop,
width: columnWidth,
sortable: true,
hidden: bHidden
});
}
}
// Now we have our JSON data, and list of Column Headings and Models, we can create our jqGrid.
CreateJQGrid(JSONdata, listOfColumnModels, listOfColumnNames);
}
});
});
Ed ecco la funzione che crea l'jqGrid:
function CreateJQGrid(JSONdata, listOfColumnModels, listOfColumnNames) {
// After loading the JSON data from our webservice, and establishing the list of
// Column Names & Models, we can call this function to create the jqGrid.
$("#SegmentRulesGrid").jqGrid({
datatype: "local",
data: JSONdata,
localReader: {
id: "SegmentID", // The Primary Key field in our JSONdata
repeatitems: false
},
mtype: "GET",
colNames: listOfColumnNames,
colModel: listOfColumnModels,
rowNum: 15,
loadonce: true,
gridview: true,
autowidth: true,
height: 350,
pager: '#pager',
rowList: [15, 30, 100, 300],
rownumbers: true,
viewrecords: true,
caption: 'Segment Rules',
});
}
Spero che questo aiuti.
Ovviamente un aspetto negativo per la mia soluzione è che insiste sul fatto che si carica tutte dei tuoi dati JSON prima di visualizzarlo in una griglia, piuttosto che caricare solo una pagina di dati alla volta. Questo potrebbe essere un problema se hai una grande quantità di dati.
puoi condividere l'intero codice? qual è il formato di result.colData? –