考慮到網站首頁使用動態網頁面的話會影響伺服器效能,所以採用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>