Ajax自动刷新简单示例(带xml文件传输)
调用Ajax的前台代码
function GetData() { xmlHttp = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); var xmlDom = new ActiveXObject("MSXML2.DOMDocument"); xmlDom.async = false; var xml = "<?xml version='1.0' encoding='utf-8'?><Data></Data>"; xmlDom.loadXML(xml); var domRoot = xmlDom.selectSingleNode("Data"); var node = xmlDom.createElement("Name"); node.text = “Jery”; domRoot.appendChild(node); xmlHttp.open("POST", 'RefreshHelpPage/Refresh.ashx', true); xmlHttp.onreadystatechange = statusChange; xmlHttp.setRequestHeader("Content-Type ", "application/x-www-form-urlencoded; "); xmlHttp.send(xmlDom); } function statusChange() { if (xmlHttp.readyState == 4) { if (xmlHttp.status >= 200 && xmlHttp.status < 300) { var json = eval(xmlHttp.responseText); var name = json[0].name } else { } } } setInterval("GetData()", 5000);
被调用的一般处理程序代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Expires = -1; context.Response.Write(JsonHelper.ObjectToJSON(getList(getXML(context)))); } private static ArrayList getXML(HttpContext context) { ArrayList Names = new ArrayList(); Stream inputStream = context.Request.InputStream; StreamReader reader = new StreamReader(inputStream,Encoding.UTF8); string xml = reader.ReadToEnd(); XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(xml); XmlElement xmlElement = xmlDoc.DocumentElement; for (int i = 0; i < xmlElement.ChildNodes.Count; i++) { string Name = xmlElement.ChildNodes[i].InnerText; Names.Add(Name); } return Names; } private List<T> getList(ArrayList Names) { List<T> List = new List<T>(); try { List = getInfo(Names)//get information from bll layer } catch (Exception) { } return List; } public bool IsReusable { get { return false; } }
JSONHelper
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; /// <summary> /// Summary description for JsonHelper /// </summary> public class JsonHelper { public JsonHelper() { // // TODO: Add constructor logic here // } public static string ObjectToJSON(object obj) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch (Exception ex) { throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message); } } }