1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> 5 <title>test</title> 6 <script type="text/javascript" src="test28.js"></script> 7 </head> 8 <body> 9 <form method="post" action="?q=javascript&num=10"> 10 <input id="q" type="text" name="q" value="" /> 11 <input id="num" type="text" name="num" /> 12 <input type="submit" value="提 交" /> 13 </form> 14 </body> 15 </html>
1 //假设查询字符串是?q=javascript&num=10 2 3 function getQueryStringArgs() { 4 5 //取得查询字符串并去掉开头的问号 6 var qs = (location.search.length > 0 ? location.search.substring(1) : ""); 7 8 //保存数据的对象 9 var args = {}; 10 11 //取得每一项 12 var items = qs.split("&"); 13 var item = null, 14 name = null, 15 value = null; 16 17 //逐个将每一项添加到args对象中 18 for (var i = 0; i < items.length; i++) { 19 item = items[i].split("="); 20 name = decodeURIComponent(item[0]); 21 value = decodeURIComponent(item[1]); 22 args[name] = value; 23 } 24 return args; 25 } 26 27 var args = getQueryStringArgs(); 28 29 console.log(args["q"]); 30 console.log(args["num"]); 31 32 window.onload = function() { 33 document.getElementById("q").value = args["q"]; 34 document.getElementById("num").value = args["num"]; 35 }