20151228:AJax返回XML值
aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!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="Scripts/jquery.min.js"></script> </head> <body> <form id="form1" runat="server"> <div> <input id="txtcode" type="text" /> <input id="btn" type="button" value="检查" /> <div id="name"></div> <div id="sex"></div> <div id="birthday"></div> <div id="nation"></div> </div> </form> <script type="text/javascript"> $(document).ready(function (e) { $("#btn").click(function (e) { var code = $("#txtcode").val(); //调AJAX $.ajax({ url: "Show.ashx",//处理页面 type: "POST",//数据提交的方式,共两种POST,GET data: { code : code },//要传输的数据,JSON格式 datatype:"XML",//返回的数据格式,共三种TEXT,JSON,XML success: function (data) { //回调函数 $("#name").text($(data).find("Name").eq(0).text());//不在同一级,有两个Name时,想取哪一个用eq来控制 $("#sex").text($(data).find("Sex").text()); $("#nation").text($(data).find("Nation").text()); $("#birthday").text($(data).find("Birthday").text()); } }) }) }) </script> </body> </html>
新建处理页面时,最好不用新建窗体,而是添加→添加新项→一般处理程序,后缀名是.ashx
ashx代码:
<%@ WebHandler Language="C#" Class="Show" %> using System; using System.Web; using System.Data;//引用命名空间 using System.Linq;//引用命名空间 using System.Data.Linq;//引用命名空间 public class Show : IHttpHandler { public void ProcessRequest (HttpContext context) { //取值 string code = context.Request["code"].ToString(); //操作数据库 TestDataContext Context = new TestDataContext(); Info data = Context.Info.Where(p => p.Code == code).First(); context.Response.Write("<?xml version='1.0' ?>"); context.Response.Write("<Info>"); context.Response.Write("<Name>"+data.Name+"</Name>"); context.Response.Write("<Sex>" + data.Sex.ToString() + "</Sex>"); context.Response.Write("<Nation>" + data.Nation + "</Nation>"); context.Response.Write("<Birthday>" + data.Birthday.Value.ToString("yyyy年MM月dd日") + "</Birthday>"); context.Response.Write("<aa><Name>hello</Name></aa>"); context.Response.Write("</Info>"); context.Response.End(); } public bool IsReusable { get { return false; } } }