转自:http://www.cnblogs.com/gotoschool/archive/2013/01/23/2873548.html
前段时间,客户要求增加一个点击率的小功能,现将部分JS代码附上,对以后有所帮助。
1、通过JS读取XML文件,主要是判断各个浏览器

// 加载xml文档
var loadXML = function (xmlFile) { var xmlDoc; if (window.ActiveXObject) {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');//IE浏览器
xmlDoc.async = false;
xmlDoc.load(xmlFile);
} else if (isFirefox=navigator.userAgent.indexOf("Firefox")>0) { //火狐浏览器
//else if (document.implementation && document.implementation.createDocument) {//这里主要是对谷歌浏览器进行处理
xmlDoc = document.implementation.createDocument('', '', null);
xmlDoc.load(xmlFile);
} else{ //谷歌浏览器
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET",xmlFile,false);
xmlhttp.send(null); if(xmlhttp.readyState == 4){
xmlDoc = xmlhttp.responseXML.documentElement;
}
} return xmlDoc;
} // 首先对xml对象进行判断
var checkXMLDocObj = function (xmlFile) { var xmlDoc = loadXML(xmlFile); if (xmlDoc == null) {
alert('您的浏览器不支持xml文件读取,于是本页面禁止您的操作,推荐使用IE5.0以上可以解决此问题!');
window.location.href = '../err.html';
} return xmlDoc;
}2、将读取到的xml文件中的数据显示到html文档上

<script type="text/javascript" language="javascript"> var xmlDoc = checkXMLDocObj('../openClass.xml');//读取到xml文件中的数据
var a = document.getElementsByTagName("a");//获取所有的A标签
$(document).ready(function () { var nodes; if($.browser.msie){ // 注意各个浏览器之间的区别
nodes = xmlDoc.getElementsByTagName('collage')[0].childNodes; //读取XML文件中需要显示的数据 }
else if (isFirefox=navigator.userAgent.indexOf("Firefox")>0){
nodes = xmlDoc.getElementsByTagName('collage')[0].children; //读取XML文件中需要显示的数据 } else{
nodes = xmlDoc.getElementsByTagName('resource');
}
for (var i = 0; i < a.length; i++) { if (a[i].parentNode.nodeName == "SPAN") { for (var j = 0; j < nodes.length; j++) { var resource = nodes[j]; var url = resource.getAttribute('url'); var href=$(a[i]).attr("href"); if (href == url) { var count = resource.getAttribute('click'); var span = document.createElement("div"); var str = document.createTextNode("点击率:" + count);
span.appendChild(str); var div = a[i].parentNode.parentNode;
div.appendChild(span); break;
}
}
}
}
});
$(function(){ //通过get请求,将点击率增加
$(a).mousedown(function(){ var href = $(this).attr("href");
$.get("../receive.ashx",{url:href,rd:Math.random()}, function (msg) {
});
})
})
</script>3、通过更新ashx文件在服务器上更新对应的xml文件

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; string src = context.Request.QueryString["url"]; string path = context.Server.MapPath("openClass.xml"); //打开xml文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path); //注意不能用Xmlload()方法
XmlNodeList nodeslist = xmlDoc.SelectNodes("/collage/resource"); //找到对应的节点
foreach (XmlNode node in nodeslist)
{
XmlElement xe = (XmlElement)node; if (xe.GetAttribute("url") == src)
{ int count = int.Parse(xe.GetAttribute("click"));
count = count + 1;
xe.SetAttribute("click", count.ToString()); //更新内容 }
}
xmlDoc.Save(path); //保存
}

发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。