[英]Recieve data into javascript from entered url to webpage
I have a webpage that alerts me the with the current .href of the website.我有一个网页,用网站的当前 .href 提醒我。 However I want to be able to pass a short variable into the webpage when entering the domain name so that I later can use that in js.
但是我希望能够在输入域名时将一个短变量传递到网页中,以便我以后可以在 js 中使用它。
For example going to website localhost entering: localhost/HelloWorld should alert " HelloWorld "例如去网站 localhost 输入: localhost/HelloWorld应该提醒“ HelloWorld ”
Is this possible?这可能吗?
This is my html code:这是我的 html 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Current URL in JavaScript</title>
</head>
<body>
<script>
function getURL() {
alert("The URL of this page is: " + window.location.href);
}
</script>
<button type="button" onclick="getURL();">Get Page URL</button>
</body>
</html>
Assuming that the address is https://localhost/HelloWorld
, try window.location.pathname.split('/')[1]
.假设地址是
https://localhost/HelloWorld
,试试window.location.pathname.split('/')[1]
。
pathname
is the string /HelloWorld
that comes after the domain localhost
. pathname
是域localhost
之后的字符串/HelloWorld
。 Using split
you can split it into parts (in this case two).使用
split
您可以将其分成几部分(在本例中为两部分)。 The first part will always be an empty string.第一部分将始终是一个空字符串。 The second part will be the string
HelloWorld
in this case.在这种情况下,第二部分将是字符串
HelloWorld
。
For this to work, the web server has to serve index.html on all paths.为此,Web 服务器必须在所有路径上提供 index.html 服务。 That's standard behavior for Node.
这是 Node 的标准行为。 Otherwise, you will want to edit your web server's configuration files.
否则,您将需要编辑 Web 服务器的配置文件。
If you go to localhost/HelloWorld
the server will try to locate the HelloWorld page, which doesn't exist.如果您转到
localhost/HelloWorld
,服务器将尝试定位不存在的 HelloWorld 页面。 Instead the correct way to pass a parameter to a page is through a query string , for instance: localhost?q=HelloWorld
.相反,将参数传递给页面的正确方法是通过查询字符串,例如:
localhost?q=HelloWorld
。 You could also redirect localhost/HelloWorld
to localhost?q=HelloWorld
using a custom router, depending on your server, for instance using a .htaccess
file, if using Apache.您还可以使用自定义路由器将
localhost/HelloWorld
重定向到localhost?q=HelloWorld
,具体取决于您的服务器,例如,如果使用 Apache,则使用.htaccess
文件。
You retrieve the parameter using window.location.search
or converting to URL object and using searchParams .您可以使用
window.location.search
或转换为 URL 对象并使用searchParams来检索参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.