是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
这是我不久前创建的一个函数,我对此很满意。它不区分大小写-这很方便。此外,如果请求的QS不存在,它只返回一个空字符串。
我使用压缩版本。我发布了未压缩的新手类型,以更好地解释发生了什么。
我确信这可以优化或以不同的方式进行,以更快地工作,但它总是非常适合我的需要。
享受
function getQSP(sName, sURL) {
var theItmToRtn = "";
var theSrchStrg = location.search;
if (sURL) theSrchStrg = sURL;
var sOrig = theSrchStrg;
theSrchStrg = theSrchStrg.toUpperCase();
sName = sName.toUpperCase();
theSrchStrg = theSrchStrg.replace("?", "&") theSrchStrg = theSrchStrg + "&";
var theSrchToken = "&" + sName + "=";
if (theSrchStrg.indexOf(theSrchToken) != -1) {
var theSrchTokenLth = theSrchToken.length;
var theSrchTokenLocStart = theSrchStrg.indexOf(theSrchToken) + theSrchTokenLth;
var theLocOfNextAndSign = theSrchStrg.indexOf("&", theSrchTokenLocStart);
theItmToRtn = unescape(sOrig.substring(theSrchTokenLocStart, theLocOfNextAndSign));
}
return unescape(theItmToRtn);
}
其他回答
对于那些想要简短方法(有限制)的人:
location.search.split('myParameter=')[1]
Artem Barger回答的改进版本:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
有关改进的更多信息,请参阅:http://james.padolsey.com/javascript/bujs-1-getparameterbyname/
Roshambo jQuery方法没有处理解码URL
http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/
在return语句中添加时也添加了该功能
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
现在您可以找到更新的要点:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
下面是一种快速获取类似于PHP$_get数组的对象的方法:
function get_query(){
var url = location.search;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
用法:
var $_GET = get_query();
对于查询字符串x=5&y&z=hello&x=6,这将返回对象:
{
x: "6",
y: undefined,
z: "hello"
}
这里有一个很好的小url实用程序,带有一些很酷的糖霜:
http://www.example.com/path/index.html?silly=willy#chucky=cheese
url(); // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain'); // example.com
url('1'); // path
url('-1'); // index.html
url('?'); // silly=willy
url('?silly'); // willy
url('?poo'); // (an empty string)
url('#'); // chucky=cheese
url('#chucky'); // cheese
url('#poo'); // (an empty string)
查看更多示例并在此处下载:https://github.com/websanova/js-url#url