如何使用参数检索整个URL

How to retrieve the whole URL with parameters?

本文关键字:URL 检索 何使用 参数      更新时间:2023-09-26

我需要检索整个URL,并将参数作为字符串。例如,我需要检索以下URL:

http://www.keytometals.com/page.aspx?ID=CheckArticle&site=kts&LN=EN&NM=349

我试过使用:

document.location.href,
document.URL,
window.location.href

但它只检索URL的一部分:

http://www.keytometals.com/page.aspx

如何获取包含当前URL及其参数的字符串?

更新:我使用了

window.content.document.location.href

我得到了以下URL:

http://www.keytometals.com/page.aspx?ID=CheckArticle

不幸的是,它仍然是URL的一部分。有人能帮我如何将整个URL作为字符串吗?

谢谢!

您应该对整个URL(包括查询字符串)使用window.location.href

查看Mozilla的文档以了解更多信息和其他属性。

下面是另一篇关于如何用JavaScript解析查询字符串的好文章StackOverflow。

您只需要简单的document.location——它将包括所有内容。您需要编写自己的代码才能在?只获取查询字符串,然后在每个&处将其拆分为名称/值对;。

编辑:

实际上,您也可以使用location.search。这是我为此写的一个片段:

function loadQueryString(){ 
    var parameters = {}; 
    var searchString = location.search.substr(1); 
    var pairs = searchString.split("&"); 
    var parts;
    for(i = 0; i < pairs.length; i++){
        parts = pairs[i].split("=");
        var name = parts[0];
        var data = decodeURI(parts[1]);
        parameters[name] = data;
    }
    return parameters;
}
params = loadQueryString();
function getQueryString() {
  var key = false, res = {}, itm = null;
  // get the query string without the ?
  var qs = location.search.substring(1);
  // check for the key as an argument
  if (arguments.length > 0 && arguments[0].length > 1)
    key = arguments[0];
  // make a regex pattern to grab key/value
  var pattern = /([^&=]+)=([^&]*)/g;
  // loop the items in the query string, either
  // find a match to the argument, or build an object
  // with key/value pairs
  while (itm = pattern.exec(qs)) {
    if (key !== false && decodeURIComponent(itm[1]) === key)
      return decodeURIComponent(itm[2]);
    else if (key === false)
      res[decodeURIComponent(itm[1])] = decodeURIComponent(itm[2]);
  }
  return key === false ? res : null;
}

然后你这样使用它:

// get a single key (if it exists)
var t = getQueryString('site');
console.log(t);
// get the whole thing as an object
t = getQueryString();
console.log(t);