JavaScript 取得網頁參數值

  • 83
  • 0
  • JS
  • 2024-10-18

想取得網頁傳遞參數可透過JavaScript的方法解析網址geturlparameter

目標從 http://localhost/geturlparameter.html?id=21&name=Tom


var getUrlString = location.href;

url.searchParams.get('id'); // 回傳 21
url.searchParams.get('name'); //回傳 Tom

或是

let params = (new URL(document.location)).searchParams;
let name = params.get('id'); // 21.
let age = parseInt(params.get('name')); // Tom