簡體   English   中英

如何從 url 獲取參數?

[英]How to get a param from the url?

我有一個像這樣的 url:

http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

我需要從此頁面的 url 中獲取名為“codice”的參數,並在查詢中使用它。 我試過這段代碼:

render() {
  const params = new URLSearchParams(this.props.location.search);
  const codiceHash = params.get('codice');
  console.log(params.get('codice'))
  return (
   <div className={styles}> 
     <div className="notification">
       <h2>Prima Registrazione eseguita con successo</h2>
     </div>
     {this.saveEsegue(email, transactionHash , blockHash, now, "FR", codiceHash)}
   </div>      
  )
}

但是我從console.log得到的是null 我究竟做錯了什么?

您的 URL 無效。 你不能有#,然后是兩個? 在里面。

你的?codice 應該是 &codice

這是獲取 codice 的一種方法

 const invalidHref = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262&somethingelse" const codice = invalidHref.split("codice=")[1].split("&")[0]; console.log(codice)

這是它在有效的 URL 上的工作方式

 const params = new URLSearchParams("http://localhost:3000/#/firstregistration?panel=4&codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262") const codice = params.get("codice") console.log(codice)

URL 中的參數字符串不正確,但要從您提供的內容中獲取字符串,我會使用 RegEx。

這樣,代碼參數在 URL 中的位置無關緊要(即,您可以添加更多參數而不會破壞它。RegEx 只會將其挑選出來。)

 const url = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262"; // window.location.href; const codice = url.match(/(codice=)([a-zA-Z0-9]*)/)[2]; console.log(codice) // prints fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

我建議您使用模塊querystring來實現這一點,這是用於此目的的頂級模塊之一。

例子:

console.log(this.props.location.search);
//=> '?foo=bar'

const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

由於您只需要一個參數並且您知道它可以保存哪些值,因此我將使用正則表達式。

var r = /codice=([a-z0-9]+)&/g
var matches = r.exec('http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262')
console.log(matches[1])
>> fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

代碼片段將返回

codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

url_string改為window.location.href以獲取頁面當前的 URL

 var url_string = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262"; //window.location.href var b = url_string.substring(url_string.indexOf("?codice=") + 1); console.log(b);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM