日期:2014-05-16  浏览次数:20550 次

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

?

转载:http://www.cnblogs.com/wangsj/archive/2010/05/25/1743338.html

问题讨论:http://home.cnblogs.com/group/topic/39468.html

作者:王善军

?

?

?

?

?

我想在工具栏中动态添加按钮,至于添加什么按钮,则从后台数据库中读取信息。

后台代码(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怎么写呢?这个问题困扰了我很久。开始写了以下代码,但不成功:

?

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 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) 肯定不成功的。

?

?

我把代码改成以下所示:

?

?

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 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.a