【问题标题】:How o get site URL on server using javascript如何使用 javascript 在服务器上获取站点 URL
【发布时间】:2015-01-21 22:11:19
【问题描述】:

我正在尝试使用 javascript 获取站点基本 url。我正在使用

var pathArray = window.location.pathname.split( '/' );
var baseURL = window.location.protocol + "//" + window.location.host + "/" + pathArray[1]+'/';

这适用于mysite.com/project1,但不适用于mysite.com

如何检查这两个网址?我必须向 url 发送 ajax 请求。

提前致谢。

【问题讨论】:

标签: javascript


【解决方案1】:

这个应该可以工作(取决于您对“基本 URL”的定义):

<script>
 /**
 * Get the parts of an URL.
 *
 * @param url URL to fetch information from
 * @return parts of an URL
 */
function getURLParts(url) {
    var parser = document.createElement('a');
    parser.href = url;
    return parser;
}

// Show the URL information
var parser = getBaseURL(window.location);
alert(parser.protocol);
alert(parser.host);
alert(parser.hostname);
alert(parser.port);
alert(parser.pathname);
alert(parser.hash);
alert(parser.search);
</script>

【讨论】:

    【解决方案2】:

    只需使用窗口的位置属性,例如window.location.href

    <script>
      alert(window.location.href);
    </script>

    【讨论】:

      【解决方案3】:

      我猜您需要当前网站的基本 URL。来自这个answer

      pathArray = window.location.href.split( '/' );
      protocol = pathArray[0];
      host = pathArray[2];
      url = protocol + '//' + host;
      

      【讨论】:

        【解决方案4】:

        基本 URL 应在标头中的特殊标记中定义:

        <head>
        <base href="http://example.com/project1/">
        </head>
        

        然后你可以用 Javascript 阅读它: 在现代浏览器中

        var baseURL = document.baseURI
        

        或旧版

        var baseURL = document.getElementsByTagName('base')[0].href
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-13
          • 2023-03-05
          相关资源
          最近更新 更多