URLSearchParams 为第一个查询字符串返回 null

aWe*_*per 9 html javascript

为什么时间段为空

const url = 'http://example.com?timeperiod=lasttwentyeightdays&pagesize=20'
const args =  new URLSearchParams(url);
alert('timeperiod='+args.get('timeperiod') + ' and pagesize='+ args.get('pagesize'));
Run Code Online (Sandbox Code Playgroud)

但在下面的代码中它有效

  const url = 'http://example.com?x=c&timeperiod=lasttwentyeightdays&pagesize=20'
  const args =  new URLSearchParams(url);
  alert('timeperiod='+args.get('timeperiod') + ' and pagesize='+ args.get('pagesize'));
Run Code Online (Sandbox Code Playgroud)

小智 16

您需要创建一个 URL 对象,然后使用以下命令检索参数url.search

const url = new URL('http://example.com?timeperiod=lasttwentyeightdays&pagesize=20');

const args =  new URLSearchParams(url.search);

console.log(`timeperiod=${args.get('timeperiod')} and pagesize=${ args.get('pagesize')}`);
Run Code Online (Sandbox Code Playgroud)

  • 或者简单地[`url.searchParams`](//developer.mozilla.org/docs/Web/API/URL/searchParams)。 (7认同)
  • 如果您想要当前站点的查询参数,请使用 document.location.search。 (2认同)