ashx檔案,.net一般處理常式。繼承IHttpHandler介面,HttpContext實現個別HTTP請求。
實現:利用本地SQL2000預設的 northwind 資料庫
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
/*---------------------------自訂代碼----------------------------*/
string str = @"server = .;uid =sa;password = sa;database = northwind";
//取資料庫中的表
SqlConnection Con = new SqlConnection(str);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("select * from Employees", Con);
Con.Open();
sda.Fill(ds);
Con.Close();
//將表填充到DataTable
DataTable dt = ds.Tables[0];
// 構造輸出資料流格式
StringBuilder strPart = new StringBuilder();
strPart.Append("<table>");
for (int i = 0; i < 5; i++)
{
strPart.AppendFormat("<tr><td><a href ='Default.aspx?id={0}'>{1}</a></td></tr>", dt.Rows[i]["EmployeeID"],dt.Rows[i]["LastName"]);
}
strPart.Append("</table>");
string s = strPart.ToString();
//根據HTTP局部請求返迴流到頁面
context.Response.Write(s);
}
public bool IsReusable
{
get {
return false;
}
}
}
運行下這個ASHX檔案將地址複製下來
在靜態頁面調用這個ASHX檔案
<!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>
<script type="text/jscript">
function list(url,divList) //ASHX檔案的地址,留輸出DIV的ID(參數)
{
var xmlHttp;
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = new XMLHttpRequest();
}
xmlHttp.open("get",url,true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
document.getElementById(divList).innerHTML =xmlHttp.responseText;
}
}
}
xmlHttp.send(null);
}
</script>
</head>
<body onload ="list('http://localhost:14379/WebHtmlPartDynamic/Handler.ashx','divList')">
<div id="divList">
</div>
<div id ="divtest">
<input id="Button1" type="button" value="button" onclick ="list('http://localhost:14379/WebHtmlPartDynamic/Handler.ashx','divtest')"/>
</div>
</body>
</html>