正在使用jqxgrid在html页面的网格中显示数据。
为了从本地json数据加载数据,jqxgrid说下面的代码可以工作。
var source ={
datatype: "json",
datafields: [{ name: 'name' },{ name: 'type' },
{ name: 'calories', type: 'int' },
{ name: 'totalfat' },{ name: 'protein' },],
localdata: jsonData
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
width: 670,
source: dataAdapter,
theme: theme,
columnsresize: true,
columns: [
{ text: 'Name', datafield: 'name', width: 250 },
{ text: 'Beverage Type', datafield: 'type', width: 250 },
{ text: 'Calories', datafield: 'calories', width: 180 },
{ text: 'Total Fat', datafield: 'totalfat', width: 120 },
{ text: 'Protein', datafield: 'protein', minwidth: 120 }
]
});
});
这将有效。但我的问题是假设我需要动态生成这个数据域&列值。我为这两个生成了json字符串,并将其存储在2个变量中,如
jsonStr = '[{ name: 'name' },{ name: 'type' },{ name: 'calories', type: 'int' },
{ name: 'totalfat' },{ name: 'protein' },]'
和
jsonColsStr='[{ text: 'Name', datafield: 'name', width: 250 },
{ text: 'Beverage Type', datafield: 'type', width: 250 },
{ text: 'Calories', datafield: 'calories', width: 180 },
{ text: 'Total Fat', datafield: 'totalfat', width: 120 },
{ text: 'Protein', datafield: 'protein', minwidth: 120 }
]'
和jqxgrid加载代码将如下所示。
var source ={datatype: "json",
datafields: jsonStr,
localdata: jsonData
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
width: 670,
source: dataAdapter,
theme: theme,
columnsresize: true,
columns: jsonColsStr
});
});
但这对我不起作用.. ??任何人都可以帮我解决这个问题。?
答案 0 :(得分:0)
我认为'columns'设置需要一个Array,但是你要传递一个String。
答案 1 :(得分:0)
你可以试试..
jsonColsStr = "[" +
" { text: \"Name\", datafield: \"name\", width: 250 }," +
" { text: \"Beverage Type\", datafield: \"type\", width: 250 }"
"]"
var myColsObject = eval(jsonColsStr); // change to json object
和....
$("#jqxgrid").jqxGrid(
{
width: 670,
source: dataAdapter,
theme: theme,
columnsresize: true,
columns: myColsObject // use the object
});
答案 2 :(得分:0)
您需要先转换为JSON对象然后传递它
var jsonStr = '[{ "name" : "name" }, { "name": "type" }, { "name" : "calories", "type" : "int" }, { "name" : "totalfat" }, { "name" : "protein" }]';
var objectJson = JSON.parse(jsonStr);
console.log(objectJson);
var source = {
datatype: "json",
datafields: objectJson,
localdata: jsonData
};