是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
如果您使用的是jQuery,那么可以使用一个库,例如jQueryBBQ:返回按钮和查询库。
…jQueryBBQ提供了一个完整的.depam()方法,以及哈希状态管理、片段/查询字符串解析和合并实用程序方法。
编辑:添加参数示例:
var DeparamExample=函数(){var params=$.depam.querystring();//nameofram是来自url的参数的名称//如果ajax使用哈希刷新,下面的代码将获取参数if(typeof params.nameofram==“undefined”){params=jQuery.departam.frage(window.location.href);}if(typeof params.nameofram!=“undefined”){var paramValue=params.nameofram.toString();}};
如果您只想使用纯JavaScript,可以使用。。。
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
由于新的HTML历史API,特别是History.pushState()和History.replaceState(),URL可能会发生更改,这将使参数及其值的缓存无效。
此版本将在每次更改历史记录时更新其内部参数缓存。
其他回答
var getUrlParameters = function (name, url) {
if (!name) {
return undefined;
}
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
url = url || location.search;
var regex = new RegExp('[\\?&#]' + name + '=?([^&#]*)', 'gi'), result, resultList = [];
while (result = regex.exec(url)) {
resultList.push(decodeURIComponent(result[1].replace(/\+/g, ' ')));
}
return resultList.length ? resultList.length === 1 ? resultList[0] : resultList : undefined;
};
可靠地做这件事比一开始想象的要复杂得多。
其他答案中使用的location.search很脆弱,应该避免使用-例如,如果有人搞砸了,并在?查询字符串。在我看来,URL在浏览器中自动转义的方式有很多种,这使得decodeURIComponent非常强制性。许多查询字符串是由用户输入生成的,这意味着对URL内容的假设非常糟糕。包括非常基本的东西,比如每个键都是唯一的,甚至有一个值。
为了解决这个问题,这里提供了一个可配置的API,并提供了健康的防御性编程。请注意,如果您愿意对某些变量进行硬编码,或者如果输入不能包含hasOwnProperty等,则可以将其大小减半。
版本1:返回包含每个参数的名称和值的数据对象。它有效地消除了重复,并始终尊重从左到右找到的第一个。
function getQueryData(url, paramKey, pairKey, missingValue, decode) {
var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;
if (!url || typeof url !== 'string') {
url = location.href; // more robust than location.search, which is flaky
}
if (!paramKey || typeof paramKey !== 'string') {
paramKey = '&';
}
if (!pairKey || typeof pairKey !== 'string') {
pairKey = '=';
}
// when you do not explicitly tell the API...
if (arguments.length < 5) {
// it will unescape parameter keys and values by default...
decode = true;
}
queryStart = url.indexOf('?');
if (queryStart >= 0) {
// grab everything after the very first ? question mark...
query = url.substring(queryStart + 1);
} else {
// assume the input is already parameter data...
query = url;
}
// remove fragment identifiers...
fragStart = query.indexOf('#');
if (fragStart >= 0) {
// remove everything after the first # hash mark...
query = query.substring(0, fragStart);
}
// make sure at this point we have enough material to do something useful...
if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
// we no longer need the whole query, so get the parameters...
query = query.split(paramKey);
result = {};
// loop through the parameters...
for (i = 0, len = query.length; i < len; i = i + 1) {
pairKeyStart = query[i].indexOf(pairKey);
if (pairKeyStart >= 0) {
name = query[i].substring(0, pairKeyStart);
} else {
name = query[i];
}
// only continue for non-empty names that we have not seen before...
if (name && !Object.prototype.hasOwnProperty.call(result, name)) {
if (decode) {
// unescape characters with special meaning like ? and #
name = decodeURIComponent(name);
}
if (pairKeyStart >= 0) {
value = query[i].substring(pairKeyStart + 1);
if (value) {
if (decode) {
value = decodeURIComponent(value);
}
} else {
value = missingValue;
}
} else {
value = missingValue;
}
result[name] = value;
}
}
return result;
}
}
版本2:返回一个具有两个相同长度数组的数据映射对象,一个用于名称,另一个用于值,每个参数都有一个索引。此格式支持重复名称,并故意不消除重复名称,因为这可能就是您希望使用此格式的原因。
function getQueryData(url, paramKey, pairKey, missingValue, decode) {
var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;
if (!url || typeof url !== 'string') {
url = location.href; // more robust than location.search, which is flaky
}
if (!paramKey || typeof paramKey !== 'string') {
paramKey = '&';
}
if (!pairKey || typeof pairKey !== 'string') {
pairKey = '=';
}
// when you do not explicitly tell the API...
if (arguments.length < 5) {
// it will unescape parameter keys and values by default...
decode = true;
}
queryStart = url.indexOf('?');
if (queryStart >= 0) {
// grab everything after the very first ? question mark...
query = url.substring(queryStart + 1);
} else {
// assume the input is already parameter data...
query = url;
}
// remove fragment identifiers...
fragStart = query.indexOf('#');
if (fragStart >= 0) {
// remove everything after the first # hash mark...
query = query.substring(0, fragStart);
}
// make sure at this point we have enough material to do something useful...
if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
// we no longer need the whole query, so get the parameters...
query = query.split(paramKey);
result = {
names: [],
values: []
};
// loop through the parameters...
for (i = 0, len = query.length; i < len; i = i + 1) {
pairKeyStart = query[i].indexOf(pairKey);
if (pairKeyStart >= 0) {
name = query[i].substring(0, pairKeyStart);
} else {
name = query[i];
}
// only continue for non-empty names...
if (name) {
if (decode) {
// unescape characters with special meaning like ? and #
name = decodeURIComponent(name);
}
if (pairKeyStart >= 0) {
value = query[i].substring(pairKeyStart + 1);
if (value) {
if (decode) {
value = decodeURIComponent(value);
}
} else {
value = missingValue;
}
} else {
value = missingValue;
}
result.names.push(name);
result.values.push(value);
}
}
return result;
}
}
如果您不想使用JavaScript库,可以使用JavaScript字符串函数来解析window.location。将此代码保存在外部.js文件中,您可以在不同的项目中反复使用它。
// Example - window.location = "index.htm?name=bob";
var value = getParameterValue("name");
alert("name = " + value);
function getParameterValue(param)
{
var url = window.location;
var parts = url.split('?');
var params = parts[1].split('&');
var val = "";
for ( var i=0; i<params.length; i++)
{
var paramNameVal = params[i].split('=');
if ( paramNameVal[0] == param )
{
val = paramNameVal[1];
}
}
return val;
}
有很多方法可以检索URI查询值,我更喜欢这个方法,因为它很短,而且效果很好:
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
Node.js的源代码中有一个健壮的实现https://github.com/joyent/node/blob/master/lib/querystring.js
TJ的qs也执行嵌套参数解析https://github.com/visionmedia/node-querystring