工学1号馆

home

在JavaScript中获取请求的URL参数[正则]

Wu Yudong    July 16, 2018     HTML5+CSS3   563   

对于这样的URL请求地址:http://tp5.com/index/index/hello.html?test=ddd&name=thinkphp

要获取 name参数的值,使用thinkphp很容易实现

<?php
namespace app\index\controller;
use think\Request;
class Index {
    public function hello(Request $request) {
        echo '请求参数:';
        dump($request->param());
        echo 'name:'.$request->param('name');
    }
}

但是要在前台js代码中获取请求的参数的值,应该怎么做呢?

<script>
function GetLocationParam(param){
	var request = {
		QueryString : function(val) {
		var uri = window.location.search;
		var re = new RegExp("" +val+ "=([^&?]*)", "ig");
		return ((uri.match(re))?(decodeURI(uri.match(re)[0].substr(val.length+1))):'');
	    }
	}
	return request.QueryString(param);
}
var uid=GetLocationParam("uid");
</script>

用该属性window.location.search获取页面 URL 地址:

window.location 对象所包含的属性

属性 描述
hash 从井号 (#) 开始的 URL(锚)
host 主机名和当前 URL 的端口号
hostname 当前 URL 的主机名
href 完整的 URL
pathname 当前 URL 的路径部分
port 当前 URL 的端口号
protocol 当前 URL 的协议
search 从问号 (?) 开始的 URL(查询部分)

js 脚本捕获页面 GET 方式请求的参数?其实直接使用 window.location.search 获得,然后通过 split 方法结合循环遍历自由组织数据格式。

如果文章对您有帮助,欢迎点击下方按钮打赏作者

Comments

No comments yet.
To verify that you are human, please fill in "七"(required)