如何通过JavaScript获取当前的.php或.html文件名?

如何通过JavaScript获取当前的.php或.html文件名?,javascript,php,html,Javascript,Php,Html,我可以通过JavaScript获取当前的.php或.html文件名吗?脚本位于current.php或.html的外部文件中,因此需要该current.html的名称文件名为.php: <!DOCTYPE html> <html> <head> ... <script src="js/Script.js" type="text/javascript"></script> </head> <body&

我可以通过JavaScript获取当前的.php或.html文件名吗?脚本位于current.php或.html的外部文件中,因此需要该current.html的名称文件名为.php:

<!DOCTYPE html>
<html>

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

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

...
...
我尝试过,但变量值为空,可能是因为我当前使用的是本地主机。任何可以在本地和远程主机上工作的操作?

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

一定是这样的:

var page = window.location.href;

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

一定是这样的:

var page = window.location.href;

下面是获取完整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重写为()时,url文件名将为空

示例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
var filename='';警报(文件名);
//输出:ex:/opt/lampp/htdocs/demo/index.php
var url2=filename.substr(filename.lastIndexOf('/')+1);
//输出:ex:index.php

下面是获取完整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重写为()时,url文件名将为空

示例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
var filename='';警报(文件名);
//输出:ex:/opt/lampp/htdocs/demo/index.php
var url2=filename.substr(filename.lastIndexOf('/')+1);
//输出:ex:index.php

取决于您运行服务器的方式<代码>窗口。位置可能有帮助,但取决于您的路由算法。对于例如,如果你在这个页面上运行,你实际上不会得到php或html,因为uri路由将不会显示它可能的重复。请说明为什么soln of不工作,因为它使用了与你接受的答案相同的
window.location.pathname
。对不起,我的错误。实际上,我使用了'var fileName=location.href.split(“/”).slice(-1);`解决方案,因为它很短。我不能删除这个问题,自己做国旗。再次抱歉。这取决于您运行服务器的方式<代码>窗口。位置可能有帮助,但取决于您的路由算法。对于例如,如果你在这个页面上运行,你实际上不会得到php或html,因为uri路由将不会显示它可能的重复。请说明为什么soln of不工作,因为它使用了与你接受的答案相同的
window.location.pathname
。对不起,我的错误。实际上,我使用了'var fileName=location.href.split(“/”).slice(-1);`解决方案,因为它很短。我不能删除这个问题,自己做国旗。再次抱歉。只是在一个基本的实现中。如果在php窗口中使用模板引擎或路由,则location将不会看到任何相关内容。例如,本页将给出如何通过javascript获取当前php或html文件名的
/questions/38341122/。不是html或servre文件名是的,你是对的,这段代码很好,以防URL有脚本名。他说不起作用。这个问题有什么不同?你给我看的这篇文章是GurebuOnly问题的一个基本实现的替代方案。如果在php窗口中使用模板引擎或路由,则location将不会看到任何相关内容。例如,本页将给出如何通过javascript获取当前php或html文件名的
/questions/38341122/。不是html或servre文件名是的,你是对的,这段代码很好,以防URL有脚本名。他说不起作用。这个问题有什么不同?你给我看的这篇文章是古里布问题的另一个选择