Javascript獲取HTML靜態頁面參數傳遞值示例

獲取HTML靜態頁面參數傳遞值能夠利用split函數來按參數切成數組、利用正則表達式來獲取。

例一
利用正則表達式來獲取
var LocString = String(window.document.location.href);
function getQueryStr(str) {
var rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi").exec(LocString), tmp;
if (tmp = rs) {
return tmp[2];
}
// parameter cannot be found
return "";
}
調用方法
document.getElementById("user").value = getQueryStr("user");
document.getElementById("password").value = getQueryStr("password");
document.getElementById("sysno").value = getQueryStr("sysno");
例二
利用split函數來按參數切成數組
<script>
urlinfo=window.location.href; //獲取當前頁面的url
len=urlinfo.length;//獲取url的長度
offset=urlinfo.indexOf("?");//設置參數字符串開始的位置
newsidinfo=urlinfo.substr(offset,len)//取出參數字符串 這裏會得到相似「id=1」這樣的字符串
//by www.jbxue.com
newsids=newsidinfo.split("=");//對得到的參數字符串按照「=」進行分割
newsid=newsids[1];//獲得參數值
alert("您要傳遞的參數值是"+newsid);
</script>
不過必定要記得 這個方法只是針對含有參數的url有用 ,若是對方用了POST方法傳遞參數, url中是不會含有參數的因此這個技巧只對GET方法或者指定了參數的url有用哦
完整的實例
aa.htm是參數輸滲入滲出界面
bb.htm是參數接收處理界面
aa.htm
<html>
  <head>
  </head>
  <body>
  <script>
  function submit()
  {
  var input1 = document.getElementById("inputid");
  window.open("bb.htm?inputStr=" + input1.value);//傳入參數
  }
  </script>
  <input type = "text" id = "inputid">
  <input type = "button" onclick = "submit()" value = "提交">
  </body>
  </html>
  bb.htm:
  <html>
  <head>
  <script>
  //得到參數的方法
  var request =
  {
  QueryString : function(val)
  {
  var uri = window.location.search;
  var re = new RegExp("" +val+ "=([^&?]*)", "ig");
  return ((uri.match(re))?(uri.match(re)[0].substr(val.leng th+1)):null);
  }
  }
  </script>
  </head>
  <body>
  <script>
  //調用方法得到參數
  var rt = request.QueryString("inputStr");
  alert(rt);
  </script>
  </body>
  </html>
bb.htm
<html>
  <head>
  <title>test</title>
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  <SCRIPT LANGUAGE="JavaScript">
  <!--
  var request = {
  QueryString : function(val) {
  var uri = window.location.search;
  var re = new RegExp("" +val+ "=([^&?]*)", "ig");
  return ((uri.match(re))?(uri.match(re)[0].substr(val.leng th+1)):null);
  }
  }
  var a = request.QueryString ("a");
  var b = request.QueryString ("b");
  var c = request.QueryString ("c");
  if ((a != null)){a=a} else{a="參數A空"}
  if ((b != null)){b=b} else{b="參數B空"}
  if ((c != null)){c=c} else{c="參數C空"}
  document.writeln("參數A: " + a);
  document.writeln("<br>參數B: " + b);
  document.writeln("<br>參數C: " + c);
  //-->
  </SCRIPT>
  </head>
  <body>
  <form name="form1" action="?">
  請輸入參數值:<br>
  <SCRIPT LANGUAGE="JavaScript">
  document.writeln("A:<input type='text' name='a' value='"+a+"'><br>");
  document.writeln("B:<input type='text' name='b' value='"+b+"'><br>");
  document.writeln("C:<input type='text' name='c' value='"+c+"'><br>");
  </SCRIPT>
  <input type="submit" name="Submit" value="提交參數查觀效果">
  </form>
  </body>
  </html>
相關文章
相關標籤/搜索