XML是一种常见的数据,其应用也非常广泛。现在新建一个名为xmlgrid.html网页,其内容如下:
<!DOCTYPE html PUBLIC “-//W3C//DTDHTML 4.01//EN”>
<html>
<head>
<meta http-equiv=”Content-Type”content=”text/html; charset=UTF-8; user-scalable=no”>
<title>XML表格</title>
<link rel=”stylesheet”type=”text/css” href=”resources/css/ext-all.css”/>
<scripttype=”text/javascript” src=”bootstrap.js”></script>
<script type=”text/javascript” src=”xmlgrid.js”></script>
</head>
<body>
<div id=”myDataGrid”width=”100%” height=500></div>
</body>
</html>
然后新建一个xmlgrid.xml文件,其内容如下:
<?xml version=”1.0” encoding=”UTF-8”?>
<MyXML>
<student>
<name>张三</name>
<gender>男</gender>
<studentNO>2012001</studentNO>
<height>170</height>
<birthday>1985 9/1 12:00am</birthday>
</student>
<student>
<name>王芳</name>
<gender>女</gender>
<studentNO>2012003</studentNO>
<height>160</height>
<birthday>1985 10/10 12:00am</birthday>
</student>
<student>
<name>王五</name>
<gender>男</gender>
<studentNO>2012002</studentNO>
<height>168</height>
<birthday>1983 5/21 12:00am</birthday>
</student>
</MyXML>
最后,新建一个xmlgrid.js文件,在该文件中添加加载上面xml文件的代码,如下:
Ext.require([ //添加需要引用的库
‘Ext.grid.*’,
‘Ext.data.*’,
‘Ext.util.*’,
‘Ext.state.*’
]);
Ext.onReady(function(){
//1定义表格列数据模型,包括列名称、数据类型
Ext.define(‘studenetInfo’, {
extend: ‘Ext.data.Model’,
fields: [
{name: ‘name’}, //姓名为字符串
{name: ‘gender’},//性别也为字符串
{name: ‘studentNO’,type: ‘int’, convert: null,defaultValue: undefined},//学号为int
{name: ‘height’,type: ‘float’, convert: null,defaultValue: undefined},//高度为float
{name: ‘birthday’, type: ‘date’,dateFormat: ‘Yn/j h:ia’,defaultValue: undefined}//生日为date
],
idProperty: ‘name’//ID属性
});
//2 创建数据对象
var store = Ext.create(‘Ext.data.Store’, {
model: ‘studenetInfo’,
autoLoad: true, //自动加载
proxy: {
type: ‘ajax’,
url: ‘xmlgrid.xml’,//xml文件
reader: {
type: ‘xml’,
record: ‘student’,
idProperty: ‘name’,
totalRecords: ‘@total’
}
}
});
//3 创建表格
var grid = Ext.create(‘Ext.grid.Panel’, {
store: store,
columns: [
{text: “姓名”, width: 100, dataIndex: ‘name’, sortable: true},
{text: “学号”, width: 60, dataIndex: ‘studentNO’, sortable: true},
{text: “性别”, width: 60, dataIndex: ‘gender’, sortable: true},
{text: “身高”, width: 60, dataIndex: ‘height’, sortable: true},
{text: “出生时间”, flex: 1, dataIndex: ‘birthday’, renderer : Ext.util.Format.dateRenderer(‘m/d/Y’),sortable: true}
],
title:’XML数据表格’,
renderTo:’myDataGrid’,
width: 500,
height: 200
});
Ext.MessageBox.alert(“xml表格”,”这是来自于xml的表格数据”);
});
以上js文件中的内容与前面一例中基本相似,只是在创建数据对象store的时候有些差别,原先的表格数据直接来源于定义的数组,所以store的data就直接来源于这个定义的数组,但是现在store的数据要来源于xml文档,通过proxy可以读取xml文件(proxy用于从某个途径读取原始数据,如MemoryProxy等),通过reader来读取数据,如下:
var store = Ext.create(‘Ext.data.Store’, {
model: ‘studenetInfo’,
autoLoad: true, //自动加载
proxy: {
type: ‘ajax’,
url: ‘xmlgrid.xml’,//xml文件
reader: {
type: ‘xml’,
record: ‘student’,
idProperty: ‘name’,
totalRecords: ‘@total’
}
}
});
值得注意的是,尽管这三个文件xmlgrid.html、xmlgrid.js和xmlgrid.xml存放在同一路径下,但是必须要在服务器上浏览才能加载xml数据,如在IIS上发布然后浏览,其结果如下图所示: