利用ashx和ajax实现表格的异步填充

这个例子是为了解答一个网友的问题而写的。使用场景就是,希望在ashx中返回DataTable,然后在页面中进行异步调用和显示。原先他的做法是想用json格式返回数据。

因为DataTable可以直接序列化为XML格式,所以我比较推荐用XML返回。而不是再去解析为json之类的格式。

1. 创建ashx文件

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

using System.Data;

namespace WebApplication1
{
    /// 
    /// $codebehindclassname$ 的摘要说明
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class GetData : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";
            context.Response.Charset = "UTF-8";
            DataTable dt = new DataTable("Employees");
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");

            for (int i = 0; i < 50; i++)
            {
                DataRow row = dt.NewRow();
                row[0] = i;
                row[1] = "员工"+i.ToString();
                dt.Rows.Add(row);
            }


            dt.WriteXml(context.Response.OutputStream);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

这个文件如果直接访问的话,是类似下面这样的返回结果

image

 

2.编写页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>


   
   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 runat="server">
    <title>
    
    title>
    <script src="jquery-1.3.2-vsdoc.js" type="text/javascript">
     
     script>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值