我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
当前回答
使用这个
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
其他回答
我用了这个,很管用。 http://codesheet.org/codesheet/NF246Tzs
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var first = getUrlVars()["id"];
也许你应该给JS牙医看看?(免责声明:代码是我写的)
代码:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"
使用牙医JS,你基本上可以在所有字符串上调用extract()函数(例如,document.URL.extract()),你会得到所有找到的参数的HashMap。它还可以自定义处理分隔符等。
缩小版< 1kb
另一种解决方案使用jQuery和JSON,因此您可以通过对象访问参数值。
var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
var stringJson = "{";
for(var i=0;i<params.length;i++)
{
var propVal = params[i].split("=");
var paramName = propVal[0];
var value = propVal[1];
stringJson += "\""+paramName+"\": \""+value+"\"";
if(i != params.length-1) stringJson += ",";
}
stringJson += "}";
// parse string with jQuery parseJSON
param = $.parseJSON(stringJson);
}
假设您的URL是http://example.com/?search=hello+world&language=en&page=3
在此之后,只需要像这样使用参数:
param.language
返回
en
最有用的用法是在页面加载时运行它,并利用全局变量在任何需要参数的地方使用它们。
如果参数包含数值,则只需解析该值。
parseInt(param.page)
如果没有参数,param将只是一个空对象。
var RequestQuerystring; (窗口。Onpopstate = function () { var匹配, pl = /\+/g, //用空格替换加法符号的正则表达式 搜索= /([^&=]+)=?([^&]*)/g, decode =函数(s){返回decodeURIComponent(s)。替换(pl, " "));}, Query = window.location.search.substring(1); RequestQuerystring = {}; While (match = search.exec(查询)) RequestQuerystring[decode(match[1])] = decode(match[2]); })();
RequestQuerystring现在是一个包含所有参数的对象
只是想展示一下我的代码:
function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}