如何使用网站网址查找文件夹

时间:2014-01-28 13:06:52

标签: javascript

我的网站上有UpFiles文件夹。

我想在下面的代码中定义struploadurl。

当我在localhost运行这个网站时,它工作正常。

但是当我在不同的服务器上部署我的网站时,它将无法工作所以我在我的代码中使用了“window.location.href”。

  function Initialisation() {   
  // Want path same as below like url.
  //  var struploadurl = "http://localhost/MyProject/UpFiles/uploadsave.aspx";      
  // where arr[0] = http , arr[2] =Server Name and arr[3] =Projectname  

    var url = window.location.href;
    var arr = url.split("/");         
    var result = arr[0] + "//" + arr[2] + "//" + arr[3];
    var strPath = result + "/UpFiles/uploadsave.aspx";
    alert(strPath);    

}

问题是,当我使用本网站的端口时,它将无法正常工作。我想要一个通用的解决方案,以便在没有端口或使用端口部署我的网站时获得struploadurl。

对于Exampple当我使用“htp:// Servrname / MyProject”部署我的站点时,上面的代码将起作用。

当我使用“htps://ehost.test.com:446 /”部署我的网站时,上面的代码将不起作用。

3 个答案:

答案 0 :(得分:1)

使用windows.location对象。它具有识别主机和端口所需的所有属性,而不是手动尝试解析url字符串。

host : localhost:800"   
hostname : "localhost"  
href : "http://localhost:800/test/"
pathname : "/test/"
port :"800"
protocol : "http:"  
search : ""

答案 1 :(得分:1)

试试这个:

function Initialisation() {   
  // Want path same as below like url.
  //  var struploadurl = "http://localhost/MyProject/UpFiles/uploadsave.aspx";      
  // where arr[0] = http , arr[2] =Server Name and arr[3] =Projectname  

    var url = window.location.href;

    var strPath = "/UpFiles/uploadsave.aspx";
    var host = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');;
    var relativePath = url.substr(host.length+1,url.length - host.length-1);
    var rootFolder = relativePath.substr(0,relativePath.indexOf("/"));
    result = host + "/" + rootFolder + strPath;

    alert(rootFolder);    
    alert(relativePath);    
    alert(result);    

}

答案 2 :(得分:0)

function Initialisation()
{
    var _location = document.location.toString();
    var applicationNameIndex = _location.indexOf('/', _location.indexOf('://') + 3);
    var applicationName = _location.substring(0, applicationNameIndex) + '/';
    var webFolderIndex = _location.indexOf('/', _
    location.indexOf(applicationName) + applicationName.length);
    var webFolderFullPath = _location.substring(0, webFolderIndex);

    alert(webFolderFullPath);
}