js/jquery的get方式请求数据时获取URL问号后的参数方法函数
原理:将url字符串以“=”分割成两部分,取第二部分就可以了
//获取url参数
function GetArgsFromHref(sHref, sArgName)
{
var args = sHref.split("?");
var retval = "";
if(args[0] == sHref) /*参数为空*/
{
return retval; /*无需做任何处理*/
}
var str = args[1];
args = str.split("&");
for(var i = 0; i < args.length; i ++)
{
str = args[i];
var arg = str.split("=");
if(arg.length <= 1) continue;
if(arg[0] == sArgName) retval = arg[1];
}
return retval;
}
例如网址:http://localhost/list.html?cid=1
如果访问时需要获取cid的参数可以参照如下方式:
<script src="js/getParameter.js"></script>
<script>
$(function () {
var search = location.search;
alert(search); //获取URL中?后的句子
var string = search.split("=")[1]; //分割取出cid
alert(string);
var cid = getParameter("cid"); //通过getParameter获取
alert(cid);
});
</script>
其中getParameter.js内容为:
//根据传递过来的参数name获取对应的值
function getParameter(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
var r = location.search.substr(1).match(reg);
if (r!=null) return (r[2]); return null;
}
如果参数值为中文直接获取时候显示“乱码”解决:
var rname = getParameter("rname");
alert(rname);//若参数值是中文会乱码
if (rname) {
var rname = window.decodeURIComponent(rname);//decode解码
}
alert(rname); //重新输出正常显示
2、js/jquery 获取url传递参数,js获取url?号后面的参数(一个或多个)
第一种方法:
(获取一个)
detail.html?order_id=10
<script language="javascript">
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
</script>
调取
$(document).ready(function(){
var a=GetRequest();
var order_id = a['order_id'];
// console.log(order_id)
Detail(order_id);
})
获取两个的(仔细看差别)
detail.html?order_id=10?uid=3
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("?");
console.log(strs)
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
}
}
return theRequest;
}
调用
$(document).ready(function(){
var a=GetRequest();
var order_id = a['order_id'];
var uid = a['uid'];
// console.log(order_id)
//console.log(uid)
Detail(order_id,uid);
})
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634704.html