发一个相对地址转绝对地址的函数
<script type="text/javascript">
<!--
mapURL=function(baseURL,href){
if(/^http:/.test(href)){return href};
var p1=baseURL.replace(/^http:|/?.*$|//$/g,"").split("/");
if(p1.length>1&&//w+/./w+$/.test(p1[p1.length-1])){p1.pop()}
if(href.charAt(0)=="/"){return "http://"+p1[0]+href};
if(!/^/././//.test(href)){return "http://"+p1.join("/")+"/"+href};
var p2=href.split("/");
for(var i=0;i<p2.length;i++){
if(p2[i]==".."&&p1.length>1) p1.pop();
else break;
};
p2.splice(0,i);
return "http://"+p1.join("/")+"/"+p2.join("/").replace(//././//g,"");
};
alert(mapURL("http://www.baidu.com/time","/g.htm"));
alert(mapURL("http://www.baidu.com/time/2008/","../g.htm"));
alert(mapURL("http://www.baidu.com/time/2008/","http://www.qq.com"));
//-->
</script>
javascript实现相对路径转绝对路径
今天在研究jQuery ajax功能的时候遇到一个问题,通过$.load(”url a”) Load一个网页的链接后获取到的地址信息是相对于当前运行ajax程序的网页的绝对地址。
比如我在 c:/xxxx/a.html 网页运行
$.load(”http://www.romotc.com a”).each(
function(){
alert($(this).attr(”href”));
}
);
www.romotc.com 网页中有一个链接 <a href=”/a.html”>a boby</a>
则弹出的信息为 c:/a.html
即/转换成了当前驱动器根路径
假如在www.baidu.com/xxxx/b.html运行上述ajax代码弹出的信息为http://www.baidu.com/a.html
/转换成了当前域名的根。
那么怎么才能转换成为真正的绝对地址呢?
废话少说看代码吧:
mapURL=function(baseURL,href){
if(/^http:/.test(href)){return href};
var p1=baseURL.replace(/^http:|/?.*$|//$/g,”").split(”/”);
if(p1.length>1&&//w+/./w+$/.test(p1[p1.length-1])){p1.pop()}
if(href.charAt(0)==”/”){return “http://”+p1[0]+href};
if(!/^/././//.test(href)){return “http://”+p1.join(”/”)+”/”+href};
var p2=href.split(”/”);
for(var i=0;iif(p2[i]==”..”&&p1.length>1) p1.pop();
else break;
};
p2.splice(0,i);
return “http://”+p1.join(”/”)+”/”+p2.join(”/”).replace(//././//g,”");
};
alert(mapURL(”http://www.baidu.com/time”,”/g.htm”));
alert(mapURL(”http://www.baidu.com/time/2008/”,”../g.htm”));
alert(mapURL(”http://www.baidu.com/time/2008/”,”http://www.qq.com”));