结构
主页面 Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
tr, td {
border: solid red;
}
img {
width:50px;
height:50px;
}
</style>
<script>
//创建Ajax
var xmlRequest;
function create() {
xmlRequest = new XMLHttpRequest();
}
//判断状态触发事件
function readyRequest() {
if (xmlRequest.readyState == 4) {
if (xmlRequest.status == 200) {
document.getElementById("show").innerHTML = xmlRequest.responseText;
}
}
}
//发送请求
function sendRequest() {
create();
xmlRequest.onreadystatechange = readyRequest;
xmlRequest.open("GET","Handler1.ashx", true)
xmlRequest.send(null);
}
</script>
</head>
<body>
<-- 显示盒子 -->
<div id="show"> </div>
<script>
window.onload = function () {
//窗体加载的时候加载数据
sendRequest();
}
</script>
</body>
</html>
一般处理程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Ajax0
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//拼写一个HTML
StringBuilder sb = new StringBuilder();
//
sb.Append("<table>");
sb.Append("<tr><th>编号</th><th>名称</th><th>图片</th><th>价格</th></tr>");
//查询表
using (FoodDBEntities db = new FoodDBEntities())
{
var data = from bl in db.FoodList select bl;
foreach (var item in data)
{
sb.AppendLine(@"<tr><td>"+item.FoodID+ "</td><td>" + item.FoodName + "</td>" +
"<td><img src='images/" + item.pic + "'/></td><td>" + item.price + "</td></tr>");
}
}
sb.Append("</table>");
//输出
context.Response.Write(sb);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}