Javascript从url获取所有参数(windows.location)

时间:2014-08-19 19:04:04

标签: javascript jquery

我试图从网址获取所有参数。

示例:

http://domain.com/page?param1=values&param2=values2?param3=value3....&paramx=valuex

我正在使用它:

window.location.search.substring(1).split("&")

除了将所有参数分隔符&替换为逗号,

之外,它的工作正常

基本上上面的参数返回如下:

param1=values,param2=values2,param3=value3,....,paramx=valuex

任何想法如何才能获得参数?

1 个答案:

答案 0 :(得分:2)

请参阅MDN上的这篇文章。它回答了你的问题。 https://developer.mozilla.org/en-US/docs/Web/API/window.location

var oGetVars = {};
if (window.location.search.length > 1) {
  for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
    aItKey = aCouples[nKeyId].split("=");
    oGetVars[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";
  }
}
// alert(oGetVars.yourVar);