Can someone post a demo or a piece of code, to exemplify how to use jqpivot and loading data using ajax. Thank you.
问题:
回答1:
I would recommend you to examine the source code of free jqGrid. Look at the part of the code. It looks like
jqPivot: function (data, pivotOpt, gridOpt, ajaxOpt) {
return this.each(function () {
var $t = this, $self = $($t), $j = $.fn.jqGrid;
function pivot(data) {
...
}
if (typeof data === "string") {
$.ajax($.extend({
url: data,
dataType: "json",
success: function (data) {
pivot(jgrid.getAccessor(data, ajaxOpt && ajaxOpt.reader ? ajaxOpt.reader : "rows"));
}
}, ajaxOpt || {}));
} else {
pivot(data);
}
});
}
You will get practically directly the answer on your question. You need specify the URL to the server which provides the input data in JSON form. No other data format is supported ("xml"
, "jsonp"
and so on) directly, but you can use ajaxOpt
parameter to overwrite the parameters of the Ajax call. It's important to understand additionally, that jqGrid uses $.jgrid.getAccessor
method to read the data from the server response. The default data format should be the following:
{
"rows": ...
}
where the value of "rows" should have the same format as the data
parameter of jqPivot
if you use if without Ajax. If you have for example
{
{
"myRoot": {
"myData": ...
}
}
}
then you can use 4-th parameter of jqPivot (ajaxOpt
) as
{ reader: "myRoot.myData" }
If the response from the server is array of data:
[
...
]
or it have some non-standard form than you can use function form of reader
. For example
$("#grid").jqGrid("jqPivot", "/myUrl", {
xDimension: [{...}],
yDimension: [{...}, ...],
aggregates: [{...}],
},
{
iconSet: "fontAwesome",
cmTemplate: { autoResizable: true, width: 80 },
shrinkToFit: false,
autoResizing: { compact: true },
pager: true,
rowNum: 20,
rowList: [5, 10, 20, 100, "10000:All"]
},
{
reader: function (obj) { return obj; },
contentType: "application/json; charset=utf-8",
type: "POST",
error: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
The above code specify the reader at the function which use all the response data directly (without object with rows
property). It specifies contentType
and type
parameter of the jQuery.ajax and the callback function error
.
If all the options seems you too difficult you can load the data directy in your code with direct call of jQuery.ajax
for example and the call jqPivot
after the data are loaded (inside of success
callback or done
).