获取http://地址传递值的两种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39644462/article/details/81020137

记录学习笔记  以前参考其他网友的,记录一下,谢谢那位猿兄的分享

 
 
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
</body>
<script type="text/javascript">
	// 方法1
	function GetRequest() {

		//search 属性是一个可读可写的字符串,可设置或返回当前 URL 的查询部分(问号 ? 之后的部分)。
		var url = location.search;  
		var theRequest = new Object();

		//indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果要检索的字符串值没有出现,则该方法返回 -1。
		if(url.indexOf("?") != -1) {

			// substr(start,length) 方法可在字符串中抽取从 第start开始的指定数目的字符,长度为length。
			var str = url.substr(1);

			//split() 方法用于把一个字符串分割成字符串数组。
			strs = str.split("&");
			for(var i = 0; i < strs.length; i++) {

				//decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
				theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}
	// 调用
	var get = GetRequest();
	var id = get['id'];
	alert("方法1.传过来的id="+id);


	// 方法2
	function getQueryString(name) {
	    var url = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	    var r = window.location.search.substr(1).match(url);
	    if(r != null) return unescape(r[2]);
	    return null;
	}
	//调用
	alert("方法2.传过来的id="+ getQueryString("id"));
</script>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_39644462/article/details/81020137