使用javascript获取url参数

ztmd8pv5  于 2021-09-23  发布在  Java
关注(0)|答案(3)|浏览(288)

我试图得到一个url参数“nr”,但总是得到false

var url = window.location.href;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')

错误是什么?

v09wglhw

v09wglhw1#

使用

var url = window.location;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')

因为window.location是具有 .search 财产
而window.location.href是一个字符串,没有 .search 财产
所以你 url.searchundefined 我可以用它来演示 URL 类似于 Location 在这方面

let loc = new URL('http://example.com/?nr=1');

// loc is a placeholder for your window.location

let url = loc.href;

// here, url.search would be window.location.href.search
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
console.log(nr);

url = loc;

// here, url.search would be window.location.search
params = new URLSearchParams(url.search);
nr = params.has('nr')
console.log(nr);
oknwwptz

oknwwptz2#

从…起https://developer.mozilla.org/en-us/docs/web/api/urlsearchparams The URLSearchParams constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present. 因此,您应该只提供查询参数字符串。
e、 g.如果您的window.location.href

https://stackoverflow.com/questions/68314446/get-url-parameter-with-javascript?query=1&query_1=2&many_queries=3

然后您应该只传递查询参数urlsearchparams类,即 query=1&query_1=2&many_queries=3

hvvq6cgz

hvvq6cgz3#

下面的函数将从url返回所有参数的数组

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

  var params = getUrlVars();

  console.log(params["nr"]);

引用自https://stackoverflow.com/a/20097994/8077687

相关问题