public class GetData : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
if (context.Request["action"]=="display")
{
context.Response.Write(JsonHelper.DataTableToJson(GetAllUsers()));
}
}
static SqlConnection conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=123456");
public static DataTable GetAllUsers()
{
string sql = "select * from users";
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
public bool IsReusable
{
get
{
return false;
}
}
}
复制代码 代码如下:
public class GetData : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
if (context.Request["action"]=="display")
{
context.Response.Write(JsonHelper.DataTableToJson(GetAllUsers()));
}
}
static SqlConnection conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=123456");
public static DataTable GetAllUsers()
{
string sql = "select * from users";
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
public bool IsReusable
{
get
{
return false;
}
}
}
4. 前端调用
复制代码 代码如下:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="https://www.jb51.net/js/jquery-1.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var options = {
type: 'post',
url: "/GetData.ashx",
dataType: "json",
data: { action: "display" },
success: function(data) {
var html = "<table><tr><td>UserId</td><td>UserName</td></tr>";
$.each(data, function(i, result) {
html += "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName"] + "</td></tr>";
})
html += "</table>";
$("#divData").html(html);
}
};
$.ajax(options);
});
</script>
</head>
<body>
<form runat="server">
<div>
</div>
</form>
</body>
</html>
复制代码 代码如下:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="https://www.jb51.net/js/jquery-1.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var options = {
type: 'post',
url: "/GetData.ashx",
dataType: "json",
data: { action: "display" },
success: function(data) {
var html = "<table><tr><td>UserId</td><td>UserName</td></tr>";
$.each(data, function(i, result) {
html += "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName"] + "</td></tr>";
})
html += "</table>";
$("#divData").html(html);
}
};
$.ajax(options);
});
</script>
</head>
<body>
<form runat="server">
<div>
</div>
</form>
</body>
</html>
5. 效果图
6. 同样可以通过getJSON方法读取数据
复制代码 代码如下: