«
JavaScript静态页面值传递之URL篇

时间:2008-5-31    作者:Deri    分类: 分享


   <p>  URL篇</p><p>  能过URL进行传值.把要传递的信息接在URL上.</p><p>  Post.htm</p><code><input type="text" name="username"><br /><input type="text" name="sex"><br /><input type="button" value="Post"><br /><script language="javascript" ><br />function Post()<br />{<br />  //单个值 Read.htm?username=baobao;<br />  //多全值 Read.htm?username=baobao&sex=male;<br />  url = "Read.htm?username="+escape(document.all.username.value);<br />  url += "&sex=" + escape(document.all.sex.value);<br />  location.href=url;<br />}<br /></script></code></p><p>  Read.htm</p><code><script language="javascript" ><br />/*<br />*--------------- Read.htm -----------------<br />* Request[key]<br />* 功能:实现ASP的取得URL字符串,Request("AAA")<br />* 参数:key,字符串.<br />* 实例:alert(Request["AAA"])<br />*--------------- Request.htm -----------------<br />*/<br />var url=location.search;<br />var Request = new Object();<br />if(url.indexOf("?")!=-1)<br />{<br />  var str = url.substr(1) //去掉?号<br />  strs = str.split("&");<br />  for(var i=0;i<strs.length;i++)<br />  {<br />     Request[strs[i ].split("=")[0]]=unescape(strs[ i].split("=")[1]);<br />  }<br />}<br />alert(Request["username"])<br />alert(Request["sex"])<br /></script><script language="JavaScript"><br /><!--<br />function Request(strName)<br />{<br />var strHref = "www.abc.com/index.htm?a=1&b=1&c=测试测试";<br />var intPos = strHref.indexOf("?");<br />var strRight = strHref.substr(intPos + 1);<br />var arrTmp = strRight.split("&");<br />for(var i = 0; i < arrTmp.length; i++)<br />{<br />var arrTemp = arrTmp[i ].split("=");<br />if(arrTemp[0].toUpperCase() == strName.toUpperCase()) return arrTemp[1];<br />}<br />return "";<br />}<br />alert(Request("a"));<br />alert(Request("b"));<br />alert(Request("c"));<br />//--><br /></script><br /><script><br />String.prototype.getQuery = function(name)<br />{<br />  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");<br />  var r = this.substr(this.indexOf("?")+1).match(reg);<br />  if (r!=null) return unescape(r[2]); return null;<br />}<br />var str ="www.abc.com/index.htm?a=1&b=1&c=测试测试";<br />alert(str.getQuery("a"));<br />alert(str.getQuery("b"));<br />alert(str.getQuery("c"));<br /></script></code></p><p>  优点:取值方便.可以跨域.</p><p>  缺点:值长度有限制.</p>