使用 jQuery 从 URL 获取查询字符串

2022-08-29 23:59:28

我有以下网址:

http://www.mysite.co.uk/?location=mylocation1

我需要将从URL的值获取到一个变量中,然后在jQuery代码中使用它:location

var thequerystring = "getthequerystringhere"

$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

我如何使用JavaScript或jQuery获得该值?


答案 1

寄件人: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

这就是你需要:)

下面的代码将返回一个包含 URL 参数的 JavaScript 对象:

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

例如,如果您有以下网址:

http://www.example.com/?me=myValue&name2=SomeOtherValue

此代码将返回:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

你可以做:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];

答案 2

若要从当前 URL 检索整个查询字符串(以字符开头),可以使用?

location.search

https://developer.mozilla.org/en-US/docs/DOM/window.location

例:

// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123" 

关于检索特定的查询字符串参数,虽然存在像URLSearchParamsURL这样的类,但目前Internet Explorer不支持它们,应该避免使用它们。相反,您可以尝试如下操作:

/**
 * Accepts either a URL or querystring and returns an object associating 
 * each querystring parameter to its value. 
 *
 * Returns an empty object if no querystring parameters found.
 */
function getUrlParams(urlOrQueryString) {
  if ((i = urlOrQueryString.indexOf('?')) >= 0) {
    const queryString = urlOrQueryString.substring(i+1);
    if (queryString) {
      return _mapUrlParams(queryString);
    } 
  }
  
  return {};
}

/**
 * Helper function for `getUrlParams()`
 * Builds the querystring parameter to value object map.
 *
 * @param queryString {string} - The full querystring, without the leading '?'.
 */
function _mapUrlParams(queryString) {
  return queryString    
    .split('&') 
    .map(function(keyValueString) { return keyValueString.split('=') })
    .reduce(function(urlParams, [key, value]) {
      if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
        urlParams[key] = parseInt(value);
      } else {
        urlParams[key] = decodeURI(value);
      }
      return urlParams;
    }, {});
}

您可以像这样使用上述内容:

// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }

// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }

// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName')) { 
  console.log(urlParams.parameterName);
}