js get请求数组参数
时间: 2023-09-27 08:08:05 浏览: 57
在 JavaScript 中,可以使用以下方法来获取 URL 中的数组参数:
```javascript
// 获取 URL 中的参数
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// 获取数组参数
function getArrayParameter(name, url) {
var paramValue = getParameterByName(name, url);
if (paramValue === null) {
return [];
}
return paramValue.split(',');
}
// 示例 URL: http://example.com/?arr=1,2,3,4,5
var arr = getArrayParameter('arr');
console.log(arr); // 输出: ['1', '2', '3', '4', '5']
```
以上代码中,`getArrayParameter` 函数接受两个参数:参数名和 URL(可选)。它内部调用了 `getParameterByName` 函数来获取 URL 中的参数值,并使用 `split` 方法将字符串以逗号分隔成数组。如果参数不存在,将返回一个空数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)