【发布时间】:2017-02-01 05:55:57
【问题描述】:
我是 javascript 和 devextreme 的新手,目前正在寻找解决办法。我创建了一个加载 json 文件的网页,效果很好,但使用 devextreme 无法完成。
我有一个要包含数据的 dxDataGrid。使用 .js 文件,该数据也可以正确显示。我的 json 文件是这样的:
{
"user": [
{
"id": 0,
"name": "user0",
"mail": "user0@example.com",
"address": "examplestreet 0",
"zip": "12345",
"city": "examplecity",
"country": "examplecountry",
"dayOfBirth": "1990/01/01"
},
{
"id": 1,
"name": "user1",
"mail": "user1@example.com",
"address": "examplestreet 1",
"zip": "23456",
"city": "examplecity",
"country": "examplecountry",
"dayOfBirth": "1990/01/01"
},
{
"id": 2,
"name": "user2",
"mail": "user2@example.com",
"address": "examplestreet 2",
"zip": "34567",
"city": "examplecity",
"country": "examplecountry",
"dayOfBirth": "1990/01/01"
}
]
}
我尝试使用以下代码加载 json 文件,在 google chromes 开发人员工具下,该对象正确显示,但由于我是新手,我无法弄清楚为什么它没有加载到 dxDataGrid .
var getData = function () {
var xmlhttp = new XMLHttpRequest(),
json;
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
json = JSON.parse(xmlhttp.responseText);
console.log(json);
return json;
}
};
xmlhttp.open('GET', 'data.json', true);
xmlhttp.send();
};
var customersViewModel = {
dataGridOptions: {
dataSource: getData(),
editing: {
allowUpdating: true,
allowAdding: true,
mode: "form",
form: {
items: [{
itemType: 'group',
caption: 'Basisinformationen',
items: ['user.name', 'user.mail', {
dataField: 'dayOfBirth',
editorOptions: {
min: new Date(1960,0,1),
max: new Date(2010,11,31)
}
}]
},
{
itemType: 'group',
caption: 'Kontakt',
items: ['user.address', 'user.zip', 'user.city', 'user.country']
}]
}
},
columns: [{
dataField: 'name',
caption: 'Name',
validationRules: [{type: 'required'}]
}, {
dataField: 'mail',
caption: 'E-Mail'
}, {
dataField: 'address',
caption: 'Address'
}, {
dataField: 'zip',
caption: 'Zip-Code'
}, {
dataField: 'city',
caption: 'City'
}, {
dataField: 'country',
caption: 'Country'
}, {
dataField: 'dayOfBirth',
caption: 'Birthdate',
dataType: 'date',
format: "dd.MM.yyyy"
}]
}
};
return customersViewModel;
感谢您的建议!
编辑:json 文件正在工作,我可以调用例如
alert(json.user[0].name);
我会收到一条带有文本“user0”的警报。但是如何在 dataGrid 中实现这个功能呢?
编辑 2:我编辑了我的代码,结果如下:此代码已更改:
var getData = function () {
var deferred = $.Deferred();
var xmlhttp = new XMLHttpRequest(),
json;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
json = JSON.parse(xmlhttp.responseText);
json = Object.keys(json).map(function (k) { return json[k] });
console.log(json);
deferred.resolve(json); // json should be array here
}
};
xmlhttp.open('GET', 'data.json', true);
xmlhttp.send();
return deferred.promise();
};
dataGrid 仍然是空的。
【问题讨论】:
标签: javascript json knockout.js devextreme