JavaScript 如何检索GET参数
为了知道通过“GET”方法传递的参数,比如有时我们传递Email-id、密码和其他详细信息。出为此,我们使用以下代码段。
当您访问任何网站时,有没有想过地址栏中的问号“?”是做什么用的?让我们找出这个问号的用途。
问号的作用:
问号起分隔符的作用,后面是一个以键值对形式的查询字符串。多个键值对由“&”符号分隔。
示例:
geeksforgeeks.org/web-development?page=2&name=gfg
上面的图片显示了地址。紧跟着“?”的内容是查询字符串,其中包含两个键值对,如下所示:
- Pair 1: page = 2
- Pair 2: name = gfg
我们的任务是从每个键值对中获取相应的值,这些值也被称为GET参数。
方法1:使用地址中指定的键
URLSearchParams类接收网站的地址并搜索与提供的键相关联的值。
示例: 以下是上述方法的代码:
// Arrow function to get the parameter
// of the specified key
getParameter = (key) => {
// Address of the current window
address = window.location.search
// Returns a URLSearchParams object instance
parameterList = new URLSearchParams(address)
// Returning the respected value associated
// with the provided key
return parameterList.get(key)
}
// Gets the value associated with the key "ie"
console.log(getParameter("ie"))
输出:
2
方法2:使用URLSearchParams类的forEach属性来检索所有的GET参数
示例: 这个示例展示了上述解释的方法的使用。
// Arrow function to get all the GET parameters
getParameters = () => {
// Address of the current window
address = window.location.search
// Returns a URLSearchParams object instance
parameterList = new URLSearchParams(address)
// Created a map which holds key value pairs
let map = new Map()
// Storing every key value pair in the map
parameterList.forEach((value, key) => {
map.set(key, value)
})
// Returning the map of GET parameters
return map
}
// Gets all the getParameters
console.log(getParameters())
输出:
{"page" => "2", "name" => "gfg"}