Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端如何快速获取页面 url query 参数【热度: 888】 #1012

Open
yanlele opened this issue Oct 18, 2024 · 0 comments
Open

前端如何快速获取页面 url query 参数【热度: 888】 #1012

yanlele opened this issue Oct 18, 2024 · 0 comments
Labels
web应用场景 应用场景类问题
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Oct 18, 2024

关键词:获取 url 参数

在前端,可以通过以下几种方式快速获取页面 URL 的查询参数:

一、使用 URLSearchParams API

  1. 基本用法
    • URLSearchParams是一个内置的 JavaScript API,用于处理 URL 的查询参数。它提供了一种方便的方式来获取、设置和删除查询参数。
    • 首先,可以使用window.location.search获取 URL 的查询字符串,然后将其传递给URLSearchParams构造函数来创建一个URLSearchParams对象。
    • 例如:
const urlParams = new URLSearchParams(window.location.search);
  1. 获取单个参数值
    • 可以使用get方法来获取指定参数的值。例如,要获取名为paramName的参数值,可以使用以下代码:
const paramValue = urlParams.get("paramName");
  1. 遍历所有参数
    • 可以使用forEach方法来遍历所有的参数。例如:
urlParams.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

二、手动解析查询字符串

  1. 基本思路

    • 如果不使用URLSearchParams,也可以手动解析 URL 的查询字符串。首先,获取window.location.search,它包含了查询字符串(例如?param1=value1&param2=value2)。
    • 然后,可以使用字符串的分割和遍历操作来提取参数名和参数值。
  2. 示例代码

const queryString = window.location.search.substring(1);
const params = {};
const paramPairs = queryString.split("&");
paramPairs.forEach((pair) => {
  const [key, value] = pair.split("=");
  if (key) {
    params[key] = decodeURIComponent(value);
  }
});

在这个例子中,首先提取查询字符串,然后将其分割成参数对数组。对于每个参数对,再次分割得到参数名和参数值,并将其存储在一个对象中。最后,可以通过params对象来访问各个参数的值。

三、使用第三方库

  1. 库的选择

    • 有一些第三方库也提供了方便的方法来处理 URL 的查询参数。例如,qs库是一个流行的用于处理查询字符串的库。
    • 可以使用npmyarn安装qs库:npm install qsyarn add qs
  2. 使用示例

import qs from "qs";

const queryString = window.location.search.substring(1);
const params = qs.parse(queryString);

在这个例子中,使用qs.parse方法将查询字符串解析为一个对象,其中键是参数名,值是参数值。

@yanlele yanlele added the web应用场景 应用场景类问题 label Oct 18, 2024
@yanlele yanlele added this to the milestone Oct 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web应用场景 应用场景类问题
Projects
None yet
Development

No branches or pull requests

1 participant