URL参数解析问题

 

 

 

请编写一个JavaScript函数 parseQueryString,它的用途是把URL参数解析为一个对象,如:var url = ”http://www.taobao.com/index.php?key0=0&key1=1& key2=2…..”
var obj = parseQueryString(url);
alert(obj.key0)  // 输出0

 

传入参数:

 

<script type="text/javascript">
var getQuery = function(query) {
var oQuery = {};
var iBegin = query.indexOf("?");
var sQuery = query.substring(iBegin + 1);
var aQuery = sQuery.split("&"); ;
for (var i = 0; i < aQuery.length; i++) {
var k = aQuery[i].indexOf("=");
if (k == -1) continue;
var key = aQuery[i].substring(0, k);
var value = aQuery[i].substring(k + 1);
oQuery[key]
= value;
}
return oQuery;
}
var test = getQuery("http://www.taobao.com/index.php?key0=0&key1=1&key2=2");

</script>

 

 直接读取网址:

1 <script type="text/javascript">
2 var parseQueryString = function() {
3 var args = new Object();
4 var query = window.location.search.substring(1);
5 var pairs = query.split("&");
6 for (var i = 0; i < pairs.length; i++) {
7 var pos = pairs[i].indexOf("=");
8 if (pos == -1) continue;
9 var argname = pairs[i].substring(0, pos);
10 var value = pairs[i].substring(pos + 1);
11
12 args[argname] = value;
13 }
14 return args;
15 }
16
17 var args = parseQueryString();
18 alert(args.key1);
19 </script>

 

posted @ 2010-03-24 13:57  ued  阅读(2614)  评论(0编辑  收藏  举报