【问题标题】:How to query parameters correctly in JS?如何在JS中正确查询参数?
【发布时间】:2022-01-04 06:34:41
【问题描述】:

我正在尝试查询参数localhost:8888?title=associate&name=John,并且我已经编写了下面的代码,但是编辑器在if-else 语句中显示错误。整个概念不正确吗?这个想法是,如果没有参数,它将使用默认值“who”和“department”。

const handleRequest = (request) => {
  const url = new URL(request.url);
  const params = url.searchParams;
  let who = "employee";
  let department = "admin";
       
  if (params.has("title") || params.has("name")) {
    return new Response(`Please address your request to ${params.get("title")} called ${params.get("name")}.`);     
  } else {
    return new Response(`Please address your request to ${who} in the ${department}.`);
  }
};

【问题讨论】:

  • 不是 OR 在您的 if 语句中。将其替换为||,意思是“或”。
  • 是的,刚刚更正了。对不起。
  • 谢谢,这行得通。仍然想知道为什么代码不只返回一个参数。如果查询只是 ?title=trainee,它不会使用“name”的默认值,而是给出 null。有四个不同的 if-else 语句听起来不对。

标签: javascript parameters


【解决方案1】:

URLSearchParams 对象提供了很多方法(如get(param), has(param))来访问查询字符串参数。

const url = new URL(
  'http://example.com/path/index.html?message=hello&who=world'
);
url.searchParams.get('message'); // => 'hello'
url.searchParams.get('missing'); // => null
//So you can simply use
let messageParam = url.searchParams.get("message") || "default value";

您可以在这里阅读更多信息

https://dmitripavlutin.com/parse-url-javascript/#31-parsing-query-string


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2023-01-31
    • 2021-03-26
    • 2023-01-30
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2021-04-12
    相关资源
    最近更新 更多