<script> // 設置或獲取整個 URL 爲字符串 // 文件訪問 file:///F:/phpStud/PHPTutorial/WWW/CasPHP/public/js/js_url.html // 域名訪問 http://casphp.com/js/js_url.html console.log(window.location.href); //設置或獲取 URL 的協議部分 console.log(window.location.protocol); //http: file: console.log(location.protocol); //http: 或者 file: // 設置或獲取 URL 的主機部分 console.log(window.location.host); //casphp.com // 設置或獲取與 URL 關聯的端口號碼 console.log(window.location.port); //80 // 設置或獲取與 URL 的路徑部分(就是文件地址) // 文件訪問 file:///F:/phpStud/PHPTutorial/WWW/CasPHP/public/js/js_url.html?a=123 // 返回值 /F:/phpStud/PHPTutorial/WWW/CasPHP/public/js/js_url.html // 域名訪問 http://casphp.com/js/js_url.html?a=123 // 返回值 /js/js_url.html console.log(window.location.pathname); // 設置或獲取 href 屬性中跟在問號後面的部分 // http://casphp.com/js/js_url.html?a=123 console.log(window.location.search); // ?a=123 // 中文自動轉碼 http://casphp.com/js/js_url.html?a=%E4%B8%AD%E5%9B%BD console.log(window.location.search); // ?a=%E4%B8%AD%E5%9B%BD //設置或獲取 href 屬性中在井號“#”後面的分段 // http://casphp.com/js/js_url.html#cc?a=123 console.log(window.location.hash); // #cc?a=123 console.log(window.location.search); // 返回爲空 // 中文自動轉碼 http://casphp.com/js/js_url.html#dd?a=%E4%B8%AD%E5%9B%BD console.log(window.location.hash); // #dd?a=%E4%B8%AD%E5%9B%BD //js 獲取路由參數 function getUrlParam(){ // 取得參數 var query_param=window.location.search; // 截取? 後面的字符串,以& 連接符分割字符串 var new_query=query_param.substring(1).split('&'); // 定義存放對象 var query_obj={}; new_query.forEach(e=>{ // 分割後 後轉爲字符串,如果參數需要數值類型,調用時要處理一下 let list=e.split('='); // 解碼 let key=decodeURI(list[0]); let val=decodeURI(list[1]); // 去除空格 let new_key=key.replace(/(^\s*)|(\s*$)/g,''); let new_val=val.replace(/(^\s*)|(\s*$)/g,''); // 存入對象 query_obj[new_key]=new_val }); return query_obj } // 調用示例 var url_query=getUrlParam(); // http://casphp.com/js/js_url.html?a=123 console.log(url_query.a);// 123 // http://casphp.com/js/js_url.html?a=%E4%B8%AD%E5%9B%BD console.log(url_query.a);// 中國 console.log(url_query.b); // undefined </script>