我有这样的网址:
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"));在现代浏览器中
在现代浏览器中,您有 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获取查询字符串?
发布评论