1. 程式人生 > >利用Ajax實現的一個DataGrid例子

利用Ajax實現的一個DataGrid例子

利用Ajax的技術非同步呼叫伺服器端的Web Service,生成一個在客戶端分頁的DataGrid。

首先來看看我們的Web Servcie,它利用傳遞過來的SQL生成資料集,採用標準的DataGrid控制元件利用RenderControl輸出為標準的HTML。

namespace GenricAjaxWS
{
 [WebService(Namespace="http://localhost/GenricAjaxWS/")]
 public class GenricAjaxWS : System.Web.Services.WebService
 {
  SqlConnection con;
  SqlDataAdapter da;
  SqlCommand cmd;
  DataSet ds;

  public GenricAjaxWS()
  {
   InitializeComponent();
   con=new SqlConnection(ConfigurationSettings.AppSettings["Connect"]);
   da=new SqlDataAdapter("",con);
   cmd=new SqlCommand("",con);
   ds=new DataSet("TahaSchema");
   
  }

// 省略系統生成的

  
  /// <summary>
  /// 生成DataGrid的HTML
  /// </summary>
  [WebMethod]
  public string getGrid(string sqlStr,int pageIndex)
  {
   da.SelectCommand.CommandText=sqlStr;
   da=new SqlDataAdapter(sqlStr,con);
   da.Fill(ds,"myTable");

   DataGrid dataGrid = new DataGrid();
   dataGrid.AutoGenerateColumns = true;
   dataGrid.DataSource = ds.Tables["myTable"].DefaultView;
   dataGrid.AllowPaging = true;
   dataGrid.PageSize = 4;
   dataGrid.PagerStyle.Visible = false;
   dataGrid.CurrentPageIndex = pageIndex;
   try
   {
    dataGrid.DataBind();
   }
   catch(Exception)
   {
    
   }
   StringWriter wr = new StringWriter();
   HtmlTextWriter writer = new HtmlTextWriter(wr);
   dataGrid.RenderControl(writer);
   string gridHtml = wr.ToString();
   wr.Close();
   writer.Close();
   DropDownList ddl_Pager = new DropDownList();
   ddl_Pager.Attributes.Add("onchange","goToPage(this.value)");
   string pager="";
   for(int i=0;i<dataGrid.PageCount;i++)
   {
    ListItem lItem = new ListItem(i.ToString(),i.ToString());
    ddl_Pager.Items.Add(lItem);
    if(i==pageIndex)
    {
     pager += "[<span style=/"background-color:#ffdd11;width:20px;align:center/"><a href=/"#/" onclick=/"goToPage('"+i+"')/">"+i+"</a></span>]";
    }
    else
    {
     pager += "[<span style=/"width:20px;align:center/"><a href=/"#/" onclick=/"goToPage('"+i+"')/" >"+i+"</a></span>]";
    }
   }
   ddl_Pager.SelectedIndex = pageIndex;
   wr = new StringWriter();
   writer = new HtmlTextWriter(wr);
   ddl_Pager.RenderControl(writer);
   string pagerHtml = "<input type='button' value='<' onclick='goToPrevPage()'>";
   pagerHtml += wr.ToString();
   pagerHtml += "<input type='button' value='>' onclick='this.disabled=goToNextPage()'>";
   wr.Close();
   writer.Close();
   return pager+pagerHtml+"<br>"+gridHtml;   
  }
 }
}

在利用Ajax來完成一個非同步的Web Service。

AjaxFuncs.js


var xmlhttp;
var ph;
var fillGrid_Str_SQL="";
var currentPageIndex ;
function fillGrid(myPH,str_Sql,pageIndex){ 
 ph = window.document.getElementById(myPH);
 fillGrid_Str_SQL = str_Sql;
 currentPageIndex = pageIndex;

 if(window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange=fillGrid_Change;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
    }
    else if (window.ActiveXObject)
        {
        try
            {
            xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
            }
        catch(e)
            {
            try
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){}
        }
                        
        if(xmlhttp)
        {
            try
            {
            xmlhttp.onreadystatechange=fillGrid_Change;
            xmlhttp.open("GET",url,false);
            xmlhttp.send();
            }
            catch(e){} 
        }
    }
}

function fillGrid_Change()
{
 if(xmlhttp.readyState==4&&xmlhttp.status==200)
 {

// 輸出Web Service返回的標準HTML語句
  var row =  xmlhttp.responseXML.selectNodes(".//"); 
  ph.innerHTML = row[1].text;
 }
}

function goToPage(pageIndex){
 fillGrid(ph.id,fillGrid_Str_SQL,pageIndex)
}

function goToNextPage(){
 try{ 
  fillGrid(ph.id,fillGrid_Str_SQL,parseInt(currentPageIndex)+1);
  return false;
 }
 catch(e){
  return true;
 }
}

function goToPrevPage(){
 fillGrid(ph.id,fillGrid_Str_SQL,parseInt(currentPageIndex)-1)
}

最後就是客戶端的頁面了,非常簡單

<html>
  <head>
    <title>AjaxGrid</title>
  <script language="javascript" type="text/javascript" src="ajaxFuncs.js"></script>
  </head>
  <body MS_POSITIONING="GridLayout" onload="fillGrid('myPH','select * from employee',1)">
    <form id="Form1" method="post" runat="server">
  <div id="myPH" ></div>  
     </form>
  </body>
</html>

截圖