javascript 获取虚拟目录路径

JavaScript011

javascript 获取虚拟目录路径,第1张

javascript是客户端脚本,严格来讲,是获取不了虚拟目录路径的。不知道你的意思是不是要取路径?取路径的话,可以这样:在 http://10.12.30.40/ 下面的文件里加上:<div id='text'></div>

<script>

function $(o){return document.getElementById(o)}

var url=' http://10.12.30.40/index.asp'

var arr=url.split('/')

url=url.replace(arr[arr.length-1],'sdf/')

$('text').innerHTML=url

//如果你要跳转,直接这样写

location.href=url

</script>

利用js中window对象的location子对象的pathname属性,返回url所对应的网页文件的虚拟路径,其中包括网页文件的文件名。用法如下:

var str = window.location.pathname

在你举的例子中少了个端口号应该http://hostname:port/index.html

这时str 的值就为 /index.html

如果目录更深如http://hostname:port/wtccut/index.html

那么str 的值就为 /wtccut/index.html

str为网页文件的虚拟路径,如果不是你要的值你可以通过正则表达式继续截取。

你可以用

var str = window.location.hostname 获得主机名或ip地址

var str = window.location.port 获得端口号