假設我有一個名為https://randompagename.com的頁面,我知道我可以使用以下語法將 GET 引數發送到此頁面:https://randompagename.com/?parameter1="one"?meter2="two"。
我還知道在 Node.js 網路應用程式上,我有一種將這些引數放入變數的簡單方法。但是,當我使用沒有 Node.js 的純前端 Javascript 時,我通常會使用以下方法解決這個問題:
const myURL = decodeURI(window.location.href)
這樣,我發現我的頁面是https://randompagename.com/?parameter1="one"?meter2="two"然后我可以決議它,排除第一個=符號之后的所有內容,然后在&. 好吧,盡管這是功能性的,但我可能缺少一種更簡單的方法來解決這個問題。如何在不使用任何庫的情況下在頁面上獲取 GET 引數?
uj5u.com熱心網友回復:
您可以使用 URL 物件https://developer.mozilla.org/en-US/docs/Web/API/URL
如果您頁面的 URL 是https://example.com/?name=Jonathan Smith&age=18,您可以使用以下方法決議名稱和年齡引數:
let searchString = (new URL(document.location)).search; //?name=Jonathan Smith&age=18
let params = (new URL(document.location)).searchParams;
let name = params.get('name'); // is the string "Jonathan Smith".
let age = parseInt(params.get('age')); // is the number 18
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347862.html
標籤:javascript dom
