使用delphi 開發 web(四)使用ajax 與extjs互動

來源:互聯網
上載者:User

     隨著現在各種js 架構(例如extjs,Jquery)的迅猛發展,很多網站都開始使用這些架構開始設計

web 頁面,而且為了提高使用者體驗,大量使用了AJAX 技術,可以動態實現很多網頁內容,

本文就以extjs 的grid 為例,介紹一下使用webbroke的伺服器 與js 架構的互動。

先看一下下面的頁面:

這個頁面動態顯示一個人員工資表,並可以實現翻頁,這是一個典型的extjs  的grid。

其頁面代碼如下:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb3212">
<title>你好</title>

<link rel="stylesheet" type="text/css" href="/extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="/extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="/extjs/ext-all.js"></script>
<script type="text/javascript" >
Ext.onReady(function(){
    Ext.BLANK_IMAGE_URL="/extjs/resources/images/default/s.gif";
    // create the Data Store
    var store = new Ext.data.JsonStore({
        root: 'topics',
        totalProperty: 'totalCount',
        idProperty: 'threadid',
        remoteSort: true,

        fields: [
            'XH', 'XM', 'PYM', 'RSXH',
            {name: 'BYTS', type: 'int'},
            'JBGZ',
            {name:'HJ',type:'float'}, 'SFZH'
        ],
        
        proxy: new Ext.data.HttpProxy({
         url: '/web/oa?path=getdata'
        })
    });
    store.setDefaultSort('BH', 'desc');

    // pluggable renders
    function renderTopic(value, p, record){
        return String.format(
                '<b><a href="http://extjs.com/forum/showthread.php?t={2}" target="_blank">{0}</a></b><a href="http://extjs.com/forum/forumdisplay.php?f={3}" target="_blank">{1} Forum</a>',
                value, record.data.forumtitle, record.id, record.data.forumid);
    }
    function renderLast(value, p, r){
        return String.format('{0}<br/>by {1}', value.dateFormat('M j, Y, g:i a'), r.data['lastposter']);
    }

    var pagingBar = new Ext.PagingToolbar({
        pageSize: 25,
        store: store,
        displayInfo: true,
        displayMsg: '顯示人數 {0} - {1} of {2}',
        emptyMsg: "沒有資料",
        
        items:[
            '-', {
            pressed: true,
            enableToggle:true,
            text: '顯示預覽',
            cls: 'x-btn-text-icon details',
            toggleHandler: function(btn, pressed){
                var view = grid.getView();
                view.showPreview = pressed;
                view.refresh();
            }
        }]
    });

    var grid = new Ext.grid.GridPanel({
        el:'topic-grid',
        width:700,
        height:500,
        title:'人員工資表',
        store: store,
        trackMouseOver:false,
        disableSelection:true,
        loadMask: true,

        // grid columns
        columns:[{
            id: 'topic', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "編號",
            dataIndex: 'XH',
            width: 420,
           // renderer: renderTopic,
            sortable: true
        },{
            header: "姓名",
            dataIndex: 'XM',
            width: 100,
            align: 'right',
            //hidden: true,
            sortable: true
        },{
            header: "拼音碼",
            dataIndex: 'PYM',
            width: 70,
            align: 'right',
            sortable: true
        },{
            header: "本月天數",
            dataIndex: 'BYTS',
            width: 70,
            align: 'right',
            sortable: true
        },{
            id: 'lastpost',
            header: "實發工資",
            dataIndex: 'HJ',
            width: 150,
           // renderer: renderLast,
            sortable: true
        }],

        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : function(record, rowIndex, p, store){
                if(this.showPreview){
                    p.body = '<p>人事序號 :'+record.data.RSXH+'</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },

        // paging bar on the bottom
        bbar: pagingBar
    });

    // render it
    grid.render();

    // trigger the data store load
    store.load({params:{start:0, limit:25}});
});

/**
 * @class Ext.ux.SliderTip
 * @extends Ext.Tip
 * Simple plugin for using an Ext.Tip with a slider to show the slider value
 */
Ext.ux.SliderTip = Ext.extend(Ext.Tip, {
    minWidth: 10,
    offsets : [0, -10],
    init : function(slider){
        slider.on('dragstart', this.onSlide, this);
        slider.on('drag', this.onSlide, this);
        slider.on('dragend', this.hide, this);
        slider.on('destroy', this.destroy, this);
    },

    onSlide : function(slider){
        this.show();
        this.body.update(this.getText(slider));
        this.doAutoWidth();
        this.el.alignTo(slider.thumb, 'b-t?', this.offsets);
    },

    getText : function(slider){
        return slider.getValue();
          }
   });

</script>
<link rel="stylesheet" type="text/css" href="/ib/grid-examples.css" />
<!-- Common Styles for the examples -->
<link rel="stylesheet" type="text/css" href="/ib/examples.css" />
</head>
<body>
<script type="text/javascript" src="../shared/examples.js"></script><!-- EXAMPLES -->

<div id="topic-grid"></div>

</body>
</html>

這個頁面主要是使用這一句來擷取伺服器端的資料

proxy: new Ext.data.HttpProxy({
         url: '/web/oa?path=getdata'
        })

而extjs 需要的是json 資料,而URL:/web/oa?path=getdata 就是要返回對應的json 串。

getdata 的指令碼代碼為:

 <%
uses SysUtils, Classes;
var
  start,limit,sort,dir:string;
  s:string;
begin
 
 start:=request.queryfields.values['start'];
 limit:=request.queryfields.values['limit'];
 sort:=request.queryfields.values['sort'];
 dir:=request.queryfields.values['dir'];
  s:='select *  from gjj ';
 if sort<>'' then
   s:=s+' order  by "'+sort+'"'+ ' '+dir;
print(wm.datatojson( s,'0','',nil));
end.
%>

函數datatojson 的作用就是根據sql 和開始行及每頁顯示數及參數 產生資料集,並根據資料集產生

extjs 需要的JSON 串。為了產生JSON 我們使用了開源的Super Object Toolkit(呵呵,這個是免費的),

然後在伺服器端實現這個函數就可以了(本例以oracle資料庫為參考)。

function Twm.datatojson(datasql, startp, endp: string;
  inparams: tstringlist = nil): string;
var
  alljson: ISuperObject;
  datajson: ISuperObject;
  recordjson: ISuperObject;
  mycx: Twebquery;
  totalcount: string;
  starti, endi, i: integer;
begin

  if startp = '' then
    starti := 0
  else
    starti := strtoint(startp);

  alljson := TSuperObject.Create(stobject);
  mycx := Twebquery.Create(self);

  mycx.Connection := dbs  ;

  mycx.sql.clear;
  mycx.sql.add('select count(*) from (' + datasql + ')');
  if inparams <> nil then
  begin
    for i := 0 to inparams.Count - 1 do
    begin
      if inparams.Names[i] <> '' then
      begin
        mycx.Parambyname(inparams.Names[i]).AsString :=
          inparams.ValueFromIndex[i];
      end;
    end;
  end;

  try
   mycx.Open;
  except
     on E:Exception do
        begin

           result:='資料庫開啟錯誤!'+e.Message;
           exit;
        end;
 end;
  totalcount := mycx.fields[0].AsString;
  if totalcount > '0' then
  begin

    datajson := TSuperObject.Create(starray);
    with mycx do
    begin
      sql.clear;

       if endp = '' then
            endi := StrToInt(totalcount)
          else
            endi := strtoint(endp);

      sql.Add(' select * from ( select tttz.*,rownum as nnnz from (');

      sql.add(datasql);
      sql.Add(') tttz )');
      sql.Add(' where nnnz>='+IntToStr(starti + 1) +' and nnnz<='+IntToStr(starti + endi));

      if inparams <> nil then
      begin
        for i := 0 to inparams.Count - 1 do
        begin
          if inparams.Names[i] <> '' then
          begin
            mycx.Parambyname(inparams.Names[i]).AsString :=
              inparams.ValueFromIndex[i];
          end;
        end;
      end;
      try

         Open;
         except
        result:='資料庫開啟錯誤!2';
         exit;

      end;
      while not eof do
      begin
        recordjson := TSuperObject.Create(stobject);

        for i := 0 to fields.Count - 1 do
        begin
          recordjson.s[fields[i].FieldName] := fields[i].AsString;
        end;

        datajson.o[''] := recordjson;
        recordjson := nil;
        next;
      end;
    end;

    alljson.o['topics'] := datajson;

    alljson.s['totalCount'] := totalcount;

    datajson := nil;
  end;

  result := alljson.AsJSon();
  mycx.Free;
  alljson := nil;

end;

這樣我們的伺服器就可以與extjs 互動,併產生上面的頁面了。

 

呵呵,是不是很酷,很簡單?

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.