ajax 用xml传递数据

页面代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="jquery-1.7.2.js"></script>
    <script type="text/javascript">
        //创建ajax对象
        function createXmlHttpRequest() {
            if (window.ActiveXObject) {//IE浏览器
                return new ActiveXObject("Microsoft.XMLHTTP");
            }
            else {//其他浏览器
                return new XMLHttpRequest();
            }
        }
        onload = function loadTable() {
            //设置请求的路径
            var url = "GetTable.ashx";
            //创建AJAX对象
            var xhr = createXmlHttpRequest();
            //设置回调函数
            xhr.onreadystatechange = function () {
                //如果返回成功
                if (xhr.readyState == 4 && xhr.status == 200) {
                    //接受从handler中返回的值
                    var dom = xhr.responseXML;
                    //拼写html
                    var html = "<table><tr><td>编号</td> <td>姓名</td></tr>";
                    //循环遍历xml
                    for (var i = 0; i < dom.getElementsByTagName("Student").length; i++) {
                        var stu = dom.getElementsByTagName("Student")[i]
                        html += "<tr><td>" + stu.childNodes[0].text + "</td><td>" + stu.childNodes[1].text+"</td></tr>"
                    }
                    html += "</table>"
                    //将得到的html代码放入网页中
                    document.getElementById("div1").innerHTML = html;
                }
            }
            //初始化XMLGttpRequest组件
            xhr.open("GET", url, true);
            //发送请求
            xhr.send(null);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id ="div1">
            
        </div>
    </form>
</body>
</html>

 handler代码

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

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using Model;
public class GetTable : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        //设置相应的格式
        context.Response.ContentType = "text/xml";
        //编写连接字符串
        string conStr = "Data Source=.;Initial Catalog=school;Integrated Security=True";
        //创建连接对象
        SqlConnection conn = new SqlConnection(conStr);
        //编写sql语句
        string sqlStr = "select * from student";
        //创建适配器对象
        SqlDataAdapter adapter = new SqlDataAdapter(sqlStr,conn);
        //创建临时表对象
        DataTable dt = new DataTable();
        //填充表数据
        adapter.Fill(dt);
        List<Student> stuList = new List<Student>();
        //将数据封装成集合
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            stuList.Add(new Student
            {
                Id = Convert.ToInt32(dt.Rows[i]["id"].ToString()),
                Name = dt.Rows[i]["Name"].ToString(),
            });
        }
        if (stuList != null)
        {
            //创建写入对象
            XmlWriter writer = null;
            try
            {
                //创建xml序列化对象
                XmlSerializer serializer = new XmlSerializer(stuList.GetType());
                //为写入对象添加参数
                writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);
                //调用序列化的方法
                serializer.Serialize(writer, stuList);
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                } 
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public class Student
    {
        public int Id { get; set; }
        public String UserName { get; set; }
        public String Pwd { get; set; }
        public string  Name { get; set; }
    }
}

 

posted @ 2013-09-09 22:57  流浪的狸猫  阅读(524)  评论(0编辑  收藏  举报