如何从javascript检索GET参数?[重复]

2020/10/01 01:01 · javascript ·  · 0评论
http://domain.com/page.html?returnurl=%2Fadmin

对于jspage.html,怎么可以检索GET参数?

对于上面的简单示例,func('returnurl')应为/admin

但是它也应该适用于复杂的查询字符串...

window.location对象。此代码为您提供了没有问号的GET。

window.location.search.substr(1)

从您的示例它将返回 returnurl=%2Fadmin

编辑:我自由地更改了Qwerty的答案,这确实很好,正如他指出的,我完全遵循OP的要求:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
          tmp = item.split("=");
          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}

我从他的代码中删除了重复的函数执行,将其替换为变量(tmp),并且decodeURIComponent按照OP的要求添加了它。我不确定这是否是安全问题。

否则,使用普通for循环,即使在IE8中也可以使用:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&");
    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    }
    return result;
}

window.location.search会从中返回一切吗?上。下面的代码将删除?,使用split拆分为键/值数组,然后将命名属性分配给params对象:

function getSearchParameters() {
      var prmstr = window.location.search.substr(1);
      return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}

function transformToAssocArray( prmstr ) {
    var params = {};
    var prmarr = prmstr.split("&");
    for ( var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
    }
    return params;
}

var params = getSearchParameters();

然后,您可以http://myurl.com/?test=1通过调用获取测试参数params.test

tl; dr使用香草javascript的单行代码解决方案

var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})

这是最简单的解决方案不幸的是,它不处理多值键和编码字符。

"?a=1&a=%2Fadmin&b=2&c=3&d&e"
> queryDict
a: "%2Fadmin"  //overriden with last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined

多值键编码字符

请参阅如何在JavaScript中获取查询字符串值的原始答案

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab&a=%2Fadmin"
> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]



在您的示例中,您将像这样访问值:

"?returnurl=%2Fadmin"
> qd.returnurl    // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"

您应该使用URL和URLSearchParams本机函数:

let url = new URL("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")
let params = new URLSearchParams(url.search);
let sourceid = params.get('sourceid') // 'chrome-instant'
let q = params.get('q') // 'mdn query string'
let ie = params.has('ie') // true
params.append('ping','pong')

console.log(sourceid)
console.log(q)
console.log(ie)
console.log(params.toString())
console.log(params.get("ping"))

https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams
https://polyfill.io/v2/docs/features/

一种更花哨的方法::)

var options = window.location.search.slice(1)
                      .split('&')
                      .reduce(function _reduce (/*Object*/ a, /*String*/ b) {
                        b = b.split('=');
                        a[b[0]] = decodeURIComponent(b[1]);
                        return a;
                      }, {});

我这样做(要检索特定的get-parameter,在这里是“ parameterName”):

var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);

这个使用正则表达式,如果param不存在或没有值,则返回null:

function getQuery(q) {
   return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

在这里,我编写了这段代码,将GET参数转换为对象,以便更轻松地使用它们。

//Get Nav Url
function getNavUrl() {
    //Get Url
    return window.location.search.replace("?", "");
};
function getParameters(url) {
    //Params obj
    var params = {};
    //To lowercase
    url = url.toLowerCase();
    //To array
    url = url.split('&');

    //Iterate over url parameters array
    var length = url.length;
    for(var i=0; i<length; i++) {
        //Create prop
        var prop = url[i].slice(0, url[i].search('='));
        //Create Val
        var value = url[i].slice(url[i].search('=')).replace('=', '');
        //Params New Attr
        params[prop] = value;
    }
    return params;
};
//Call To getParameters
console.log(getParameters(getNavUrl()));
var getQueryParam = function(param) {
    var found;
    window.location.search.substr(1).split("&").forEach(function(item) {
        if (param ==  item.split("=")[0]) {
            found = item.split("=")[1];
        }
    });
    return found;
};

如果您不介意使用库而不是滚动自己的实现,请查看https://github.com/jgallen23/querystring

此解决方案处理URL解码:

var params = function() {
    function urldecode(str) {
        return decodeURIComponent((str+'').replace(/\+/g, '%20'));
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = urldecode(tmparr[1]);
        }
        return params;
    }

    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();

用法:

console.log('someParam GET value is', params['someParam']);

这是基于上面的Kat和Bakudan的示例的另一个示例,但是使其更加通用。

function getParams ()
{
    var result = {};
    var tmp = [];

    location.search
        .substr (1)
        .split ("&")
        .forEach (function (item) 
        {
            tmp = item.split ("=");
            result [tmp[0]] = decodeURIComponent (tmp[1]);
        });

    return result;
}

location.getParams = getParams;

console.log (location.getParams());
console.log (location.getParams()["returnurl"]);

我创建了一个简单的Javascript函数来从URL访问GET参数。

只要包含此Javascript源,就可以访问get参数。例如:在http://example.com/index.php?language=french中,该language变量可以按进行访问$_GET["language"]同样,所有参数的列表将$_GET_Params作为数组存储在变量中。以下代码段提供了Javascript和HTML:

<!DOCTYPE html>
<html>
  <body>
    <!-- This script is required -->
    <script>
    function $_GET() {
      // Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
      var href = window.location.href;
	
      // Get the protocol e.g. http
      var protocol = window.location.protocol + "//";
	
      // Get the host name e.g. www.google.com
      var hostname = window.location.hostname;
	
      // Get the pathname e.g. /files/script.php
      var pathname = window.location.pathname;
	
      // Remove protocol part
      var queries = href.replace(protocol, '');
	
      // Remove host part
      queries = queries.replace(hostname, '');
	
      // Remove pathname part
      queries = queries.replace(pathname, '');
	
      // Presently, what is left in the variable queries is : ?v=1.8.7&country=india
	
      // Perform query functions if present
      if (queries != "" && queries != "?") {
	
	// Remove question mark '?'
        queries = queries.slice(1);
	
        // Split all the different queries
        queries = queries.split("&");
		
        // Get the number of queries
        var length = queries.length;
		
        // Declare global variables to store keys and elements
        $_GET_Params = new Array();
        $_GET = {};
	
        // Perform functions per query
        for (var i  = 0; i < length; i++) {
			
          // Get the present query
          var key = queries[i];
			
          // Split the query and the value
          key = key.split("=");
			
          // Assign value to the $_GET variable
          $_GET[key[0]] = [key[1]];
			
          // Assign value to the $_GET_Params variable
          $_GET_Params[i] = key[0];
        }
      }
    }

    // Execute the function
    $_GET();
    </script>
    <h1>GET Parameters</h1>
    <h2>Try to insert some get parameter and access it through javascript</h2>
  </body>
</html>

我的解决方案扩展到@ tak3r的

当没有查询参数时,它将返回一个空对象,并支持数组表示法?a=1&a=2&a=3

function getQueryParams () {
  function identity (e) { return e; }
  function toKeyValue (params, param) {
    var keyValue = param.split('=');
    var key = keyValue[0], value = keyValue[1];

    params[key] = params[key]?[value].concat(params[key]):value;
    return params;
  }
  return decodeURIComponent(window.location.search).
    replace(/^\?/, '').split('&').
    filter(identity).
    reduce(toKeyValue, {});
}

如果您正在使用angularjs,则可以使用$routeParamsusingngRoute模块

您必须在应用程序上添加模块

angular.module('myApp', ['ngRoute'])

现在您可以使用服务 $routeParams

.controller('AppCtrl', function($routeParams) {
  console.log($routeParams); //json object 
}

要将参数作为JSON对象获取:

alert(getUrlParameters().toSource())

function explode(delim, str)
{
    return str.split(delim);
}

function getUrlParameters()
{
    var out = {};
    var str = window.location.search.replace("?", "");
    var subs = explode('&', str);
    for(var i = 0; i < subs.length; ++i)
    {
        var vals = explode('=', subs[i]);
        out[vals[0]] = vals[1];
    }
    return out;
}

您可以使用位置对象中可用的搜索功能。搜索功能提供URL的参数部分。详细信息可以在这里找到-http: //www.javascriptkit.com/jsref/location.shtml

您将必须解析所得的字符串以获取变量及其值,例如,将其分割为'='

本文地址:http://javascript.askforanswer.com/ruhecongjavascriptjiansuogetcanshuzhongfu.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!