ExtJs2.0学习系列(11)--Ext.XTemplate

XTemplate是Extjs里面的模板组件.
下面我们看个最简单的例子.
效果图:

js代码:

Ext.onReady(function(){
    //数据源
    var data={
       name:"博客园",
       read:[{
           book:'<<道不远人>>',
           date:'2007-7-7'
       },{
           book:"<<大话设计模式>>",
           date:"2006-6-6"
       }]
    }
    //呈现组件
    var mypanel=new Ext.Panel({
      width:400,
      id:"mypanel",
      title:"XtemplateData简单示例",
      renderTo:Ext.getBody()
    });
    //创建模板
    var tpl=new Ext.XTemplate(
        '<table><tr><th>名称:{name}</th></tr>',
        '<tr><td>',
        '<tpl for="read">',
             '<p>编号:{#},书:{book},日期:{date}</p>',
        '</tpl></td></tr></table>'
    );
    //重写绑定模板
    tpl.overwrite(mypanel.body,data);
})
简要说明:

/*
var tpl=new Ext.XTemplate(
        '<table><tr><th>名称:{name}</th></tr>',
        '<tr><td>',
        '<tpl for="read">',
             '<p>编号:{#},书:{book},日期:{date}</p>',
        '</tpl></td></tr></table>'
    );
tpl.compile();
    tpl.overwrite(mypanel.body,data);
*/
1.tpl.compile();//可以在创建模板后,添加tpl.compile();编译代码,速度快点.
2. tpl.overwrite(mypanel.body,data);//把数据填充到模板中去,并呈现到目标组件
3.名称:{name}//对于一维单数据对象,直接用{名称}输出,
4.,<tpl for="read">//对于多维对象(如拥有多条数据的表),使用tpl和for配合使用,会使用tpl的格式把数据一条一条输出,read为上级节点
5.{.}//对于一维对数据的对象,如color: ['Red', 'Blue', 'Black'],可以用{.}按照tpl模板逐一输出,如:
   '<tpl for="color">',
       '<div> {.}</div>',
    '</tpl>'
6.{#}//表示循环的索引
7.parent.***//在子对象中访问父对象元素,使用parent,如:{parent.name}
8.if//'<tpl if="age &gt; 1">',
            '<p>{name}</p>',
        '</tpl>',
    //if实现有条件的逻辑判断,很容易使用
9.其他几个常用的参数:
     xindex//循环模板的当前索引index(从1开始),用[]。
     xcount//循环模板循环的次数。 用[]
  举例:
   '<tpl for="read">',
             '<p>编号:{#},书:{book},日期:{date},奇偶:{[xindex%2==0?"偶数":"奇数"]},次数:{[xcount]}</p>',
        '</tpl>
10.模板成员函数(借用api下):
var tpl = new Ext.XTemplate(
    '<tpl for="kids">',
        '<tpl if="this.isGirl(name)">',
            '<p>Girl: {name} - {age}</p>',
        '</tpl>',
        '<tpl if="this.isGirl(name) == false">',
            '<p>Boy: {name} - {age}</p>',
        '</tpl>',
    '</tpl></p>', {
     isGirl: function(name){
         return name == 'Sara Grace';
     },
     isBaby: function(age){
        return age < 1;
     }
});
接下来,我们做个服务器的例子(好像很多朋友对这个要求很强烈啊)
实例演示:用模板呈现服务器数据
效果图:

html代码:

<div id="container">
  </div>
css代码:

 <style type="text/css">
        body
        {
            font-size:12px
            }
       #container
       {
           border:1px solid black;
           width:330px;
           }
       td,th
       {
           border-bottom:1px dashed black;
           }
           th
           {
               text-align:center;
               }
       .namewidth
       {
               width:120px;
           }
           .urlwidth
           {
               width:150px;
               }
    </style>
js代码:

Ext.onReady(function(){

    var mydata;
    Ext.Ajax.request({
      http://www.cnblogs.com/hannover/admin/"getXtemplateData.ashx",//服务器端地址
      success:function(request){
             mydata=request.responseText;//服务器端文本数据
             mydata=eval('('+mydata+')');//使用eval把文本数据转换为json对象
             //或者用extjs自带的方法:mydata=Ext.util.JSON.decode(mydata),效果相同
             var tpl2=new Ext.XTemplate(
             '<table><thead><tr><th> 编号</th><th class="namewidth">名称</th>< th class="urlwidth">地址</th><th>位置</th></tr>& lt;/thead><tbody>',
            '<tpl for="results">',
               '<tr><td>{#}</td><td>{linkname}</td><td>{linkurl}</td><td>{linkpos}</td><tr>',
            '</tpl></tbody></table>'
            );
            tpl2.compile();
            tpl2.overwrite(Ext.get("container"),mydata);
       
      },
      failure:function()
      {
         alert("failure!");
      }
    });
})
/***简单说明***
1.Ext.Ajax.request(),这里暂且对ajax不多谈论,后面会详细叙述
2.eval用"()"可以把规范文本转换为json对象,很重要!mydata=eval('('+mydata+')');
3.如果我们把模板创建和绑定放到ajax外面,会出错,因为ajax为异步调用,记住哦~
4.关于success函数的request参数,我截个图看看,就明白了
*/

先看看数据库数据:

字段,数据都很清楚.下面是服务器getXtemplateData.ashx的代码:

<%@ WebHandler Language="C#" Class="getXtemplateData" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public class getXtemplateData : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
       
        StringBuilder tempResult = new StringBuilder("{results:[");

        string connstr = @"Data Source=WIN-7JW7UWR0M27\MSSQL2005;Initial Catalog=xgc;Persist Security Info=True;User ID=sa;Password=************";
        SqlConnection sqlconn = new SqlConnection(connstr);
        SqlCommand comm = new SqlCommand("select * from xLink", sqlconn);
        sqlconn.Open();
        SqlDataReader sdr = comm.ExecuteReader();
        while (sdr.Read())
        {
            tempResult.Append("{id:'");
            tempResult.Append((int)sdr["id"]);
            tempResult.Append("',linkname:'");
            tempResult.Append((string)sdr["linkname"]);
            tempResult.Append("',linkurl:'");
            tempResult.Append((string)sdr["linkurl"]);
            tempResult.Append("',linkpos:");
            tempResult.Append((int)sdr["linkpos"]);
            tempResult.Append("},");
        }
        tempResult.Remove(tempResult.Length - 1, 1);//去掉多余的那个逗号
        tempResult.Append("]}");
        context.Response.Write(tempResult);//输出
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
今天对XTemplate做了个简单介绍,下篇我们开始TreePanel的学习讨论~!
最后推荐个网站:***视频网 ,谢谢支持!
============补充==========
我们在上面对基础上作个查询:
html代码为:

<div id="head"><input id="linkid" type="text" /></div>
  <div id="container">
  </div>
js代码在上面js的基础上添加下面部分:

    new Ext.Button({
         text:"查询大于指定id值的记录",
         handler:function(){
              Ext.Ajax.request({
              http://www.cnblogs.com/hannover/admin/"getXtemplateData.ashx?id="+Ext.get("linkid").dom.value,//获取文本框的值
              success:function(request){
              mydata=request.responseText;
              mydata=eval('('+mydata+')');
              tpl2.overwrite(Ext.get("container"),mydata);
              },
              failure:function()
              {
                 alert("failure!");
              }
            });
         }
     }).render(document.body,"head");
服务器GetTemplateData.ashx代码也要稍微修改下:

//主要代码
 public void ProcessRequest (HttpContext context) {
        string sql="";
        if (context.Request.QueryString["id"] != null)
        {
            sql = "select * from xLink where id>"+Convert.ToString(context.Request.QueryString["id"]);
        }
        else
        {
             sql="select * from xLink";
        }
        StringBuilder tempResult = new StringBuilder("{results:[");

        string connstr = @"Data Source=WIN-7JW7UWR0M27\MSSQL2005;Initial Catalog=xgc;Persist Security Info=True;User ID=sa;Password=673592063@qq.com";
        SqlConnection sqlconn = new SqlConnection(connstr);
        SqlCommand comm = new SqlCommand(sql, sqlconn);
        sqlconn.Open();
        SqlDataReader sdr = comm.ExecuteReader();
        while (sdr.Read())
        {
            tempResult.Append("{id:'");
            tempResult.Append((int)sdr["id"]);
            tempResult.Append("',linkname:'");
            tempResult.Append((string)sdr["linkname"]);
            tempResult.Append("',linkurl:'");
            tempResult.Append((string)sdr["linkurl"]);
            tempResult.Append("',linkpos:");
            tempResult.Append((int)sdr["linkpos"]);
            tempResult.Append("},");
        }
        tempResult.Remove(tempResult.Length - 1, 1);
        tempResult.Append("]}");
        context.Response.Write(tempResult);
    }
效果图:
 
代码有点乱!

 

posted @ 2011-02-12 10:15  hannover  阅读(761)  评论(0编辑  收藏  举报