【问题标题】:How to get current .php or .html file name by JavaScript?如何通过 JavaScript 获取当前的 .php 或 .html 文件名?
【发布时间】:2016-11-15 10:02:10
【问题描述】:

我可以通过 JavaScript 获取当前的 .php 或 .html 文件名吗?脚本在当前.php或.html的外部文件中,所以需要.php的当前.html的name文件名:

<!DOCTYPE html>
<html>

<head>
    ...
    <script src="js/Script.js" type="text/javascript"></script>
</head>

<body>
    ...
</body>
</html>

我试过this,但变量值是空的,可能是因为我目前使用的是本地主机。有什么可以在本地和远程主机上工作的事情吗?

【问题讨论】:

  • 取决于您运行服务器的方式。 window.location 可能会有所帮助,但取决于您的路由算法。为了。例如,如果您在此页面中运行,您实际上不会得到 php 或 html,因为 uri 路由不会显示它
  • 请说明为什么 stackoverflow.com/questions/2196606/… 的解决方案不起作用,因为它使用与您接受的答案相同的 window.location.pathname
  • 对不起,我的错误。真的,我使用了 `var fileName = location.href.split("/").slice(-1);` 解决方案,因为它很短。我自己无法删除这个问题并制作标志。再次抱歉。

标签: javascript php html


【解决方案1】:

下面是获取完整 URL 和 URL 文件名的简单代码:

示例 1:

var url=location.href;
var urlFilename = url.substring(url.lastIndexOf('/')+1);

输出1:

url => http://localhost/demo/index.php
urlFilename => index.php

输出2:

url => http://localhost/demo/
urlFilename => 

如果url被重写为(http://localhost/demo/),urlFilename将为空

示例 2:我不知道你是否想在 javascript 中使用 php,如果你急于获取文件名,这是一种方法。

var filename = '<?= __FILE__?>';alert(filename);
//output: ex: /opt/lampp/htdocs/demo/index.php
var url2 = filename.substr(filename.lastIndexOf('/')+1);
//output: ex: index.php

【讨论】:

    【解决方案2】:

    Window Location

    验证此文档是否可以帮助您。

    一定是这样的:

    var page = window.location.href;
    

    【讨论】:

    • 仅在初级实现中。如果您在 php window.location 中使用模板引擎或路由,将看不到任何相关内容。例如,此页面将提供/questions/38341122/how-to-get-current-php-or-html-file-name-by-javascript。不是 html 或 servre 文件名
    • 是的,你是对的,如果 URL 有脚本名称,这段代码很好。
    • 他说stackoverflow.com/questions/2196606/… 不起作用。这个问题有什么不同?
    • 你给我看的这篇文章是Gurebu问题的替代方案
    【解决方案3】:

    创建以下函数以在 JavaScript 中获取当前 .php 或 .html 文件的名称。

    const getCurrentFile = () => {
        let url = window.location.href;
        let objs = url.split("/");
        return (objs[objs.length-1]);
    }
    

    这里借助 JavaScript 的 split 函数,我们将 url 用“/”分割,然后返回最后一个元素。

    【讨论】:

      猜你喜欢
      • 2016-03-08
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2019-05-23
      相关资源
      最近更新 更多