我想在工具栏中动态添加按钮,至于添加什么按钮,则从后台数据库中读取信息。
后台代码(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怎么写呢?这个问题困扰了我很久。开始写了以下代码,但不成功:
- ToolBar = function() {
- Ext.Ajax.request({
- url: 'rolegroup.aspx',
- params: '',
- method: 'POST',
- success: function(response, options) {
- //alert('success');
- var rsp = Ext.util.JSON.decode(response.responseText);
- var total = rsp.totalProperty;
- //alert(total);
- //alert(rsp.result[0].text);
- var arrays = new Array(total);
- for (var i = 0; i < total; i++) {
- //arrays[i] = new Ext.Toolbar.Button({ text: rsp.result[i].text, iconCls: 'icon-home' });
- arrays[i] = { text: rsp.result[i].text, iconCls: 'icon-home' };
- if (i == (total - 1))
- arr += '{text:' + rsp.result[i].text + '}'
- else
- arr += '{text:' + rsp.result[i].text + '},';
- }
- arr = '{[' + arr + ']}';
- alert(arr);
- //alert(arrays.length);
- //alert(arrays[1]['text'] + ',' + arrays[1]['iconCls']);
- var o = { items: arrays };
- //Ext.apply(this, A, o); //不成功?
- Ext.apply(this, o);
- },
- failure: function() {
- Ext.Msg.alert("提示信息", "按钮加载失败,请稍后重试!");
- }
- });
- ToolBar.superclass.constructor.call(this, {
- id: 'tool_bar',
- cls: 'top-toolbar',
- })
- };
- Ext.extend(ToolBar, Ext.Toolbar);
- //在后台创建toolbar = new ToolBar();
以上代码,arrays可以成功读取后台数据,但工具栏并不能显示出相应按钮。也就是说Ext.apply(this, o)并不成功!
事实上,Ajax是异步调用后台数据的,toolbar = new ToolBar()先运行了,但并没有同时立即运行读取后台数据的代码,而是滞后的。后来再运行Ext.apply(this, o)肯定不成功的。
我把代码改成以下所示:
- SetToolButtons = function(tbr) {
- Ext.Ajax.request({
- url: 'rolegroup.aspx',
- params: '',
- method: 'POST',
- success: function(response, options) {
- var rsp = Ext.util.JSON.decode(response.responseText);
- var total = rsp.totalProperty;
- var arrays = new Array(total);
- for (var i = 0; i < total; i++) {
- arrays[i] = new Ext.Toolbar.Button({ text: rsp.result[i].text, iconCls: 'icon-home' });
- }
- tbr.add(arrays);
- tbr.addFill();
- tbr.addButton(
- {
- text: '我的桌面',
- iconCls: 'icon-desktop',
- scope: this
- });
- tbr.addSeparator();
- tbr.addButton([
- {
- text: '重新登录',
- iconCls: 'icon-user'
- },
- {
- text: '退出系统',
- iconCls: 'icon-exit'
- }]);
- },
- failure: function() {
- Ext.Msg.alert("提示信息", "按钮加载失败,请稍后重试!");
- }
- });
- };
- Ext.onReady(function() {
- Ext.QuickTips.init();
- var toolbar = new Ext.Toolbar({
- id: 'tool_bar',
- cls: 'top-toolbar'
- });
- SetToolButtons(toolbar);
- }
先创建好工具栏,我再添加按钮,而且是一次性添加好。结果运行成功!