ajax 局部刷新分页和自动搜索提示

来源:互联网 发布:linux shared 编辑:程序博客网 时间:2024/06/11 17:58

 源码下载地址:http://download.csdn.net/source/1918359

前台HTML代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>无标题页</title>
    <style type="text/css">
    a { text-decoration:none;}
    </style>
    <script type="text/javascript">
    var xmlHttp;
    function CreateXmlHttp()
    {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    function StartRequest(index)
    {
      // alert("1");
        var url="repeater.aspx?index="+index+"&key="+escape(document.getElementById("tip").value);
        //alert(url);
        //form1.btn.disabled="true";
        CreateXmlHttp();
        xmlHttp.open("GET",url,true);
        xmlHttp.setRequestHeader("Content-Type","text/html; encoding=gb2312");
        xmlHttp.onreadystatechange=getdata;
        xmlHttp.send(null);
     }
     function getdata()
     {
        
        var container=document.getElementById("container");
         if(xmlHttp.readyState==4)
      {
        if(xmlHttp.status==200)
        {

           //alert(xmlHttp.responseText);
           document.all.container.innerHTML=xmlHttp.responseText;
          // form1.btn.disabled="false";
         }
      }     
    }      
    function searchResult()
{
   
    CreateXmlHttp();
   
    document.getElementById("list").innerHTML="";
    //xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=GB2312;');
   var url="handler.ashx?keyword="+escape(document.getElementById("tip").value);
    //var url="handler.ashx?keyword="+document.getElementById("tip").value;
    xmlHttp.open("GET",url,true);
    //xmlHttp.setRequestHeader("Content-Type","text/html; encoding=gb2312");
    xmlHttp.onreadystatechange=showResult;
   
    xmlHttp.send(null);
   
}
function showResult()
{
    if(xmlHttp.readyState==4)
    {
        if(xmlHttp.status==200)
        {
           var result=xmlHttp.responseText;
           if(result!="no")
           {
              var arrayList=result.split("'");
        var list=document.getElementById("list");
        var tip=document.getElementById("tip");
              for(i=0;i<arrayList.length;i++)
          {
             //var Display="<div onclick='Search(this)' onmouseout='MouseOut(this)' onmouseover='MouseOver(this)'>"+arrayList[i]+"</div>";
                   var item=document.createElement("div");
                   item.onclick='Search(this)';
                   item.onmouseout='MouseOut(this)';
                   item.onmouseover='MouseOver(this)';
                   item.innerText=arrayList[i];
                   list.appendChild(item);
                   //list.innerHTML+=Display;
                 }
              possugg();
              list.innerHTML+="<div onclick='closeTip();' onmouseout='MouseOut(this)' onmouseover='MouseOver(this)' style='text-align:right;'><font color='#cc3366'>Close</font></div>";   
             list.style.display="block";
           //list.style.offsetTop=tip.style.
             list.style.visibility="visible";
           }
        }
    }
}
function Search(obj)
{
  document.getElementById("tip").value=obj.innerText;
  document.getElementById("list").style.visibility="hidden"; 
}
function MouseOver(obj)
{
  obj.className='over';
}
function MouseOut(obj)
{
  obj.className='out';
}
function TipMouseOut(obj)
{
  obj.style.visibility="hidden";
}
function closeTip()
{
 var o=document.getElementById('list');
 o.style.visibility='hidden';
}

function findPos(obj)
{
 var curleft = curtop = 0;
 do
 {
 curleft += obj.offsetLeft;
 curtop += obj.offsetTop;
 } while (obj = obj.offsetParent);
 return [curleft,curtop];
}
function possugg()
{
 var o=document.getElementById('list');
 var q=document.getElementById('tip');
 var p=findPos(q);
 o.style.left = p[0]+'px';
 o.style.top = p[1]+q.clientHeight+3+'px';
}
</script>

    <style type="text/css">
    .over { background-color:Blue;}
    .out  { background-color:#FFFFFF;}
    </style>
</head>

<body>
<form id="from1" action="">
<span>搜索结果</span>
<div style="height:auto; width:auto" id="container"><br /><br /><br /><br /><br /><br /></div>
<br />

<input type="text" id="tip" style="width: 123px; height: 19px" autocomplete="off" onkeyup="searchResult();"  />
    <div id="list" style="position:absolute; left: 12px; width: 150px; height: 46px; top: 196px; border:1px solid #000000; text-align:left; display:none; visibility:hidden; height:auto;" onmouseout=""></div>
  
&nbsp;
    <input type="button" id="btn"  onclick="StartRequest(0);" value="搜索" style="width: 77px; height: 23px;" />
   
</form></body>
</html>
服务器端代码(repeater.aspx.cs):

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Rep_check : System.Web.UI.Page
{
    public int pagecount,pageIndex;
    public string str;
    protected void Page_Load(object sender, EventArgs e)
    {
        pageIndex = Convert.ToInt32(Request.QueryString[0]);
        this.databind(pageIndex,Request.QueryString[1]);
       
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter swriter = new System.IO.StringWriter(sb);
        HtmlTextWriter writer = new HtmlTextWriter(swriter);
       
        Repeater1.RenderControl(writer);
        swriter.Close();
        writer.Close();
        sb.Append("<br />");
       
        for (int i = 0; i <pagecount; i++)
            sb.Append("<a href='javascript:StartRequest("+i.ToString()+");'>" + (i+1).ToString() + "&nbsp;&nbsp;</a>");
        Response.Write(str+sb.ToString());
        Response.End();
    }
    private void databind(int pageIndex,string keyword)
    {
        SqlConnection con = new SqlConnection("Data Source=MICROSOF-4215CE;Initial Catalog=musicdb;Integrated Security=True");
        try
        {

            string comstr = "getbykeyword";
            SqlCommand com = new SqlCommand(comstr, con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.Add("@keyword", SqlDbType.VarChar, 15);
            com.Parameters[0].Value = keyword;
            ////con.Open();
            ////SqlDataReader dr = com.ExecuteReader();
            ////if (!dr.HasRows)
            ////{
            ////    dr.Close();
            ////    con.Close();
            ////    Response.Redirect("noitems.aspx");
            ////    return;
            ////}
            ////dr.Close();
            SqlDataAdapter sd = new SqlDataAdapter();
            sd.SelectCommand = com;
            DataSet ds = new DataSet();
            sd.Fill(ds);
            PagedDataSource pds = new PagedDataSource();
            pds.DataSource = ds.Tables[0].DefaultView;
               str = "共有" + ds.Tables[0].Rows.Count.ToString() + "条相关信息<br />";
            pds.AllowPaging = true;
            pds.PageSize = 5;
            pds.CurrentPageIndex = pageIndex;
            pagecount = pds.PageCount;
            this.Repeater1.DataSource = pds;
            this.Repeater1.DataBind();
           
        }
        catch
        {
            if (con.State == ConnectionState.Open)
                con.Close();
        }
    }

}
repeater控件设计代码(repeater.aspx):

<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand" OnItemDataBound="Repeater1_ItemDataBound" >
    <HeaderTemplate><hr /></HeaderTemplate>
    <FooterTemplate><hr /></FooterTemplate>
    <AlternatingItemTemplate><br /></AlternatingItemTemplate>
    <ItemTemplate>
    <%# DataBinder.Eval(Container,"DataItem.customerid") %>
    <%# DataBinder.Eval (Container, "DataItem.companyname")%>
    <%# DataBinder.Eval(Container, "DataItem.contactname")%>
    <asp:LinkButton ID="delbtn" Text="Delete" runat="server" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.customerid") %>' CommandName="delete" OnClientClick="return confirm('Are you sure to delete it');"></asp:LinkButton>
    <asp:LinkButton ID="updatebtn" Text="Update" runat="server" CommandName="update" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.customerid") %>'></asp:LinkButton>
    </ItemTemplate>
    </asp:Repeater>
后台handler.ashx代码:

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

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
public class Handler : IHttpHandler
{
   
    public void ProcessRequest (HttpContext context)
    {
       
    
        string keyword =context.Server.UrlDecode(context.Request.QueryString[0].Trim());
        if (keyword != "")
        {
            SqlConnection con = new SqlConnection("Data Source=MICROSOF-4215CE;Initial Catalog=musicdb;Integrated Security=True");
            SqlCommand com = con.CreateCommand();

            com.CommandText = "select singer from singers where singer like '" + keyword + "%';" + "select song from song where song like '"+keyword+"%'";
            con.Open();
            SqlDataReader dr = com.ExecuteReader();
            string list = "";

            do
            { 
                while(dr.Read())
                list += dr.GetString(0) + "'";
            } while (dr.NextResult());
       
            con.Close();
            con.Dispose();
            com.Dispose();
            context.Response.ContentType = "text/plain";
            if (list == "")
                context.Response.Write("no");
            else
                context.Response.Write(list.Remove(list.Length - 1));
        }
        else
            context.Response.Write("no"); 
    }
 
    public bool IsReusable
    {
        get {
            return false;
        }
    }

}

 

 

原创粉丝点击