如何使用JavaScript从当前URL获取查询字符串? [英] How to obtain the query string from the current URL with JavaScript?

查看:105
本文介绍了如何使用JavaScript从当前URL获取查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的网址:

http://localhost/PMApp/temp.htm?ProjectID=462

我需要做的是在之后获取详细信息? sign(查询字符串) - 即 ProjectID = 462 。我怎样才能使用JavaScript?

What I need to do is to get the details after the ? sign (query string) - that is ProjectID=462. How can I get that using JavaScript?

到目前为止我所做的是:

var url = window.location.toString();
url.match(?);

我不知道下一步该做什么。

I don't know what to do next.

推荐答案

查看 MDN文章关于 window.location

QueryString在窗口中可用.location.search

The QueryString is available in window.location.search.

在旧版浏览器中也可以使用的解决方案

MDN提供了一个示例(在上面引用的文章中不再提供)如何获取QueryString中可用的单个键的get值。这样的事情:

MDN provide an example (no longer available in the above referenced article) of how to the get value of a single key available in the QueryString. Something like this:

function getQueryStringValue (key) {  
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would write the value of the QueryString-variable called name to the console  
console.log(getQueryStringValue("name")); 

在现代浏览器中

在现代浏览器中,您有 <$ URL界面的c $ c> searchParams 属性,返回 URLSearchParams 对象。返回的对象有许多方便的方法,包括get-method。所以上面例子的等价物是:

In modern browsers you have the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

URLSearchParams 接口也可用于解析查询字符串格式的字符串,并将它们转换为方便的URLSearchParams对象。

The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

请注意,此界面的浏览器支持仍然有限,所以如果你需要支持旧版浏览器,坚持使用第一个示例或使用 polyfill

这篇关于如何使用JavaScript从当前URL获取查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆