您的位置:首页 > 数据库

关于ExtJS的工具栏动态添加按钮(从后台数据库读取信息)

2010-05-25 10:00 751 查看
我想在工具栏中动态添加按钮,至于添加什么按钮,则从后台数据库中读取信息。

后台代码(C#)

//以下是工具栏按钮测试代码,生成JSON
string json = "[{'id': '1','text':'测试1'},{'id':'2','text':'测试2'},{'id':'4','text':'测试3'}]";
json = "{'totalProperty':'3','result':" + json + "}";
Response.Write(json);

但JS怎么写呢?这个问题困扰了我很久。开始写了以下代码,但不成功:

1 ToolBar = function() {
2
3 Ext.Ajax.request({
4 url: 'rolegroup.aspx',
5 params: '',
6 method: 'POST',
7 success: function(response, options) {
8 //alert('success');
9 var rsp = Ext.util.JSON.decode(response.responseText);
10 var total = rsp.totalProperty;
11 //alert(total);
12 //alert(rsp.result[0].text);
13 var arrays = new Array(total);
14 for (var i = 0; i < total; i++) {
15 //arrays[i] = new Ext.Toolbar.Button({ text: rsp.result[i].text, iconCls: 'icon-home' });
16 arrays[i] = { text: rsp.result[i].text, iconCls: 'icon-home' };
17 if (i == (total - 1))
18 arr += '{text:' + rsp.result[i].text + '}'
19 else
20 arr += '{text:' + rsp.result[i].text + '},';
21 }
22 arr = '{[' + arr + ']}';
23 alert(arr);
24 //alert(arrays.length);
25 //alert(arrays[1]['text'] + ',' + arrays[1]['iconCls']);
26 var o = { items: arrays };
27 //Ext.apply(this, A, o); //不成功?
28 Ext.apply(this, o);
29 },
30 failure: function() {
31 Ext.Msg.alert("提示信息", "按钮加载失败,请稍后重试!");
32 }
33 });
34
35 ToolBar.superclass.constructor.call(this, {
36 id: 'tool_bar',
37 cls: 'top-toolbar',
38 })
39 };
40
41 Ext.extend(ToolBar, Ext.Toolbar);
42
43 //在后台创建toolbar = new ToolBar();

以上代码,arrays可以成功读取后台数据,但工具栏并不能显示出相应按钮。也就是说Ext.apply(this, o)并不成功!

事实上,Ajax是异步调用后台数据的,toolbar = new ToolBar()先运行了,但并没有同时立即运行读取后台数据的代码,而是滞后的。后来再运行Ext.apply(this, o)肯定不成功的。

我把代码改成以下所示:

1 SetToolButtons = function(tbr) {
2 Ext.Ajax.request({
3 url: 'rolegroup.aspx',
4 params: '',
5 method: 'POST',
6 success: function(response, options) {
7 var rsp = Ext.util.JSON.decode(response.responseText);
8 var total = rsp.totalProperty;
9 var arrays = new Array(total);
10 for (var i = 0; i < total; i++) {
11 arrays[i] = new Ext.Toolbar.Button({ text: rsp.result[i].text, iconCls: 'icon-home' });
12 }
13 tbr.add(arrays);
14 tbr.addFill();
15 tbr.addButton(
16 {
17 text: '我的桌面',
18 iconCls: 'icon-desktop',
19 scope: this
20 });
21 tbr.addSeparator();
22 tbr.addButton([
23 {
24 text: '重新登录',
25 iconCls: 'icon-user'
26 },
27 {
28 text: '退出系统',
29 iconCls: 'icon-exit'
30 }]);
31 },
32 failure: function() {
33 Ext.Msg.alert("提示信息", "按钮加载失败,请稍后重试!");
34 }
35 });
36 };
37
38 Ext.onReady(function() {
39 Ext.QuickTips.init();
40 var toolbar = new Ext.Toolbar({
41 id: 'tool_bar',
42 cls: 'top-toolbar'
43 });
44 SetToolButtons(toolbar);
45 }
46

先创建好工具栏,我再添加按钮,而且是一次性添加好。结果运行成功!

我查了许多网友提供的资料,结合大家的思路,才有以上代码,在此衷心感谢广大网友!

希望本文对大家有帮助!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐