DIV CSS 佈局教程網

透過 window.location.search 獲取網址參數的方法
編輯:關於JavaScript     

在頁面開發中,我們常需要從網址中擷取傳入的參數。本文介紹透過 window.location.search 來實現這一功能,經實測可行。

 function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i"); var r = window.location.search.substr(1).match(reg); if (r!=null) return (r[2]); return null; } var sname = GetQueryString("name"); if(sname!=null) { var sname_ = decodeURIComponent(sname); alert(sname_); }

測試方式:存取 abcd.html?name=xyz,程式應該彈出 xyz。

這個方法透過正規表達式比對參數名稱,能準確地從查詢字串中取出對應的值,並透過 decodeURIComponent 進行解碼,避免中文等特殊字元出現亂碼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved