天天看點

使用js切割URL的參數

對于一些開發場景,不使用Jsp或freemarker及其其他的模闆引擎時,通常通過切割url獲得對應的參數,然後通過AJAX與背景互動得到對應的資料

下面是示範執行個體:

test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>切割URL</title> 

</head> 

<body> 
<a href="/LMS/test?userId=1">點選</a>
</body> 
</html>       

test2.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>三級關聯效果</title>  
<style type="text/css">  
    select{ width:100px; text-align:center;}  
</style>  
<script type="text/javascript">  

    window.onload=function(){  
  
        GetRequest();
    };  
    function GetRequest() {
          var fullURL = window.location.href;
          alert(fullURL);
           var url = location.search; //擷取url中"?"符後的字串
           var theRequest = new Object();
           alert(url);
           if (url.indexOf("?") != -1) {
              var str = url.substr(1);
              strs = str.split("&");
              alert(strs)
              for(var i = 0; i < strs.length; i ++) {
                 theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
                  alert(theRequest[strs[i].split("=")[0]]);
              }
           }
           return theRequest;
        }
</script>  
</head>  
  
<body>  

<p>測試:</p>  
</body>  
</html>