ASP.NET中AJAX 调用实例代码

2020-05-19 07:37:00易采站长站整理

1前言
最近在ASP.NET中做了一个AJAX调用 : Client端先从ASP.NET Server后台取到一个页面模板,然后在页面初始化时再从Server中取一些相关数据以实现页面模板的动态显示。具体实现为:
1) Client向 ASP.NET后台发送HTTP GET 请示
2) 后台给Client发送一个HTML模板,同时在内存中存储一个XML String (包含页面模板动态显示所需的数据)
3) Client在初始化页面时,发送AJAX请求,拿到XML String
4) 利用拿到的XML String,定制化HTMl模板,实现HTML页面模板的动态显示。
2几个关键点的简介与代码示例
2.1 ASP.NET Server端
2.1.1 用C#生成XML String
用System.Xmlnamespace下的几个类就可以实现。下面是Code sample,

ArrayList steps = new ArrayList();
String errordiscription = “Not in position”;
for (int i = 0; i < 5; i++)
{
steps.Add(new Step(@”images/1.jpg”, “step21 description”));
}
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration(“1.0”, “UTF-8”, null);
doc.AppendChild(docNode);
//add the root
XmlNode rootNode = doc.CreateElement(“Root”);
doc.AppendChild(rootNode);
//add the error description node
XmlNode errorNode = doc.CreateElement(“ErrorDescription”);
errorNode.AppendChild(doc.CreateTextNode(errordiscription));
rootNode.AppendChild(errorNode);
//add the steps node
XmlNode productsNode = doc.CreateElement(“Steps”);
rootNode.AppendChild(productsNode);
for (int i = 0; i < steps.Count; i++)
{
XmlNode productNode = doc.CreateElement(“step”);
XmlAttribute productAttribute = doc.CreateAttribute(“description”);
productAttribute.Value = ((Step)steps[i]).description;
productNode.Attributes.Append(productAttribute);
//productNode.Value = ((Step)steps[i]).imagePath;
productNode.AppendChild(doc.CreateTextNode(((Step)steps[i]).imagePath));
productsNode.AppendChild(productNode);
}
Global.Repairsteps= doc.InnerXml;

生成的XML如下:

<?xml version=”1.0″ encoding=”UTF-8″ ?>
– <Root>
<ErrorDescription>Not in position</ErrorDescription>
– <Steps>
<step description=”step21 description”>images/1.jpg</step>
<step description=”step21 description”>images/1.jpg</step>
<step description=”step21 description”>images/1.jpg</step>
<step description=”step21 description”>images/1.jpg</step>
<step description=”step21 description”>images/1.jpg</step>
</Steps>
</Root>

2.1.2 响应Ajax请求,返回XML 流
这里就只有一点需要注意,加个HTML Header,声明 Content-Type.

Response.Clear();