功能很简单,页面异步发送请求,服务器端响应的内容是XML,页面根据返回的XML填充已存在的GridView
新增页面用于展示数据
<!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 type="text/javascript">
var xmlHttp = null;
var isIE = !!window.ActiveXObject;
function createXMLHttpRequest() {
if (xmlHttp == null) {
if (window.XMLHttpRequest) {
//Mozilla 浏览器
xmlHttp = new XMLHttpRequest();
} else if (isIE) {
// IE浏览器
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('创建失败');
}
}
}
}
}
function openAjax() {
if (xmlHttp == null) {
createXMLHttpRequest();
if (xmlHttp == null) {
alert('出错');
return;
}
}
xmlHttp.open("post", "Handler.ashx", true);
xmlHttp.onreadystatechange = xmlHttpChange;
xmlHttp.send(null);
}
function xmlHttpChange() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var vehArr = xmlHttp.responseXML.getElementsByTagName('veh');
var tb = document.getElementById('<%=gv.ClientID %>');
var tr,td;
for (var i = 0, len = vehArr.length; i < len; i++) {
tr = document.createElement("tr");
td = document.createElement("td");
td.innerHTML = vehArr[i].getAttribute('id');
tr.appendChild(td);
td = document.createElement("td");
td.innerHTML = isIE ? vehArr[i].firstChild.text : vehArr[i].childNodes[1].textContent;
tr.appendChild(td);
tb.tBodies[0].appendChild(tr);
}
alert('加载完成!');
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
获取数据并填充GridView
<asp:Button ID="btn" runat="server" Text="GO" OnClientClick="openAjax();return false;" />
<br />
<asp:GridView ID="gv" runat="server">
</asp:GridView>
</form>
</body>
</html>
对应的cs文件代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gv.DataSource = new[] { new { id = 3, lsh = 1110917109126 } };
gv.DataBind();
}
}
新增处理程序用于处理异步请求
/// <summary>
/// Summary description for Handler
/// </summary>
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/xml";
string xml=@"
<root>
<head>
<code>1</code>
<message>数据下载成功</message>
<rownum>1</rownum>
</head>
<body>
<veh id='0'>
<lsh>1110917109123</lsh>
</veh>
<veh id='1'>
<lsh>1110917109124</lsh>
</veh>
<veh id='2'>
<lsh>1110917109125</lsh>
</veh>
<veh id='N'>
<lsh>N</lsh>
</veh>
</body>
</root>";
context.Response.Write(xml);
}
public bool IsReusable
{
get
{
return false;
}
}
}
需要注意的地方,在页面的cs文中 使用了匿名类,要确保运行环境支持,如不支持,请用普通的class来代替。