考虑到网站首页使用动态页面的话会影响服务器性能,所以采用javascript来实现首页的动态更新。
原理,以发新闻稿为例,当后台发出一条新闻后,通过访问数据库动态生成一个XML文件,保存新闻的信息,当打开前台页面时,使用javascript读取XML文件并显示。
后台代码:
sseEntities _db = new sseEntities();
var newsToView = (from n in _db.News select n).ToArray().Reverse().ToList();
XmlDocument xd = new XmlDocument();
XmlDeclaration xde;
xde = xd.CreateXmlDeclaration("1.0", "GBK", null);
xd.AppendChild(xde);
XmlElement newslist = xd.CreateElement("newslist");
xd.AppendChild(newslist);
XmlNode root = xd.SelectSingleNode("newslist");
XmlElement [] news = new XmlElement [4];
XmlElement [] text = new XmlElement [4];
XmlElement [] img = new XmlElement[4];
for (int i = 0; i < 4; i++)
{
news[i] = xd.CreateElement("news");
text[i] = xd.CreateElement("text");
img[i] = xd.CreateElement("img");
news[i].SetAttribute("id", i.ToString());
if (i < newsToView.Count)
{
text[i].InnerText = newsToView[i].Title;
img[i].InnerText = "Content/newsimages/slider_item1.png";
}
else
{
text[i].InnerText = "";
img[i].InnerText = "";
}
news[i].AppendChild(text[i]);
news[i].AppendChild(img[i]);
root.AppendChild(news[i]);
}
xd.Save(Server.MapPath("../Sources/News.xml"));
前台读取代码:
<script type="text/javascript">
function loadXML(xmlFile) {
var xmlDoc;集装箱运费
if (!window.ActiveXObject) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlFile, "text/xml");
} else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.load(xmlFile);
}
return xmlDoc;iphone5
}
var xmlDoc = loadXML("Sources/News.xml");
//解析xml文件,判断是否出错
if (xmlDoc.parseError.errorCode != 0) {
alert(xmlDoc.parseError.reason);
}
//获得根节点
var nodes = xmlDoc.documentElement.childNodes;
</script>