簡體   English   中英

從單個 URL 獲取多個參數的最新關鍵參數?

[英]Get the latest key param of multiple params from a single URL?

當用戶在頁面'a'中並且在forms輸入字段中寫入內容然后從頁面a到頁面b並從那里返回到頁面a時,如果用戶想要從url獲取數據,可能有兩個具有相同的名稱例如這是 url ?name=james&name=alex我的問題是如何獲得最新的“名稱”,例如 name name=alex是新的。 這是我從 url 獲得的方法:

 const query = window.location.toString().split("?")[1]; const urlParams = new URLSearchParams(query); const Name = urlParams.get("name") || props.order?.name;
 <Form.Item label={t( "orders.name")} name="name" initialValue={Name || ""}> <Input type="string" /> </Form.Item>

這個答案是從HERE采用的。

相反,您應該將您的名稱編碼為一個數組並將其設置為 name 參數。 添加新名稱時,使用Array.push(ITEM)添加到末尾,並使用Array[Array.length - 1]獲取最近添加的項目。

 //URL to array: function URLToArray(url, param) { return url.substring(url.indexOf(param + '=') + param.length + 1).split('&')[0].split('_'); } //Array to URL: function ArrayToURL(array, param) { return param + '=' + array.join('_'); } /*************************************/ //You can then use this as such: // Get Array var myArray = URLToArray('https://google.com?name=Bob_Joe_Tom&state=Alaska_Texas_Main', 'name'); console.log(myArray); // Get URL myArray.push('Steph'); //Lets add a name to the array var myNameUrl = 'www.google.com?' + ArrayToURL(myArray, 'name'); console.log(myNameUrl);

I have made this so you can have any number of arrays on the url as well, hence why I have the state value in the example, just to show it can discern between the two arrays.

可能這會對你有所幫助。

 function getLatestParamFromUrl(param="") { const url = new URL(window.location.href); const values = url.searchParams.getAll(param); const latestValues = values.length > 0? values.pop(): false; return;.latestValues && latestValues; } console.log(getLatestParamFromUrl("name"));

暫無
暫無

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

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