简体   繁体   English

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

[英]How to get current .php or .html file name by JavaScript?

Can I get the current .php or .html file name by JavaScript?我可以通过 JavaScript 获取当前的 .php 或 .html 文件名吗? The script is in the external file in respect to current .php or .html, so need the name file name of this current .html of .php:该脚本在当前 .php 或 .html 的外部文件中,因此需要 .php 的当前 .html 的名称文件名:

<!DOCTYPE html>
<html>

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

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

I tried this but the variable value was empty, maybe because currently I use the local host.我试过了,但变量值为空,可能是因为我目前使用的是本地主机。 Anything that can to do which will be work on both local and remote host?可以在本地和远程主机上执行的任何操作?

Window Location 窗口位置

Verify if this document can help you. 验证此文档是否可以为您提供帮助。

It must be something, like this: 它一定是这样的:

var page = window.location.href;

Below is the simple code to get full URL and filename of URL: 以下是获取完整URL和URL文件名的简单代码:

Example1: 范例1:

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

OUTPUT1: 输出1:

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

OUTPUT2: 输出2:

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

urlFilename will be empty in case of url is rewritten to ( http://localhost/demo/ ) 如果将url重写为( http:// localhost / demo / ),则urlFilename将为空

Example2: I do not know if you want to use php inside javascript, if you are desperate to get the filename this is one way to do it. 例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

Create following function to get the current .php or .html file's name in JavaScript.创建以下函数以在 JavaScript 中获取当前 .php 或 .html 文件的名称。

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

Here, with the help of JavaScript's split function, we splits the url with "/" and then returned the last element.在这里,借助 JavaScript 的 split 函数,我们将 url 用“/”拆分,然后返回最后一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM