简体   繁体   English

获取转义的网址参数

[英]Get escaped URL parameter

I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". 我正在寻找一个可以获取URL参数的jQuery插件,并支持此搜索字符串而不输出JavaScript错误:“格式错误的URI序列”。 If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this. 如果没有支持这个的jQuery插件,我需要知道如何修改它来支持这个。

?search=%E6%F8%E5

The value of the URL parameter, when decoded, should be: 解码后,URL参数的值应为:

æøå

(the characters are Norwegian). (字符是挪威语)。

I don't have access to the server, so I can't modify anything on it. 我无权访问服务器,因此无法对其进行任何修改。

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'): 以下是我从这里的评论中创建的内容,以及修复未提及的错误(例如实际返回null,而不是'null'):

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

What you really want is the jQuery URL Parser plugin . 你真正想要的是jQuery URL Parser插件 With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this: 使用此插件,获取特定URL参数(对于当前URL)的值如下所示:

$.url().param('foo');

If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this: 如果你想要一个带有参数名称的对象作为键和参数值作为值,你只需要调用没有参数的param() ,如下所示:

$.url().param();

This library also works with other urls, not just the current one: 此库也适用于其他网址,而不仅仅是当前网址:

$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes

Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc: 由于这是一个完整的URL解析库,您还可以从URL获取其他信息,如指定的端口,或路径,协议等:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

It has other features as well, check out its homepage for more docs and examples. 它还有其他功能,请查看其主页以获取更多文档和示例。

Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. 而不是写你自己的URI解析器这有点儿工作在大多数情况下,这一特定目的的,用一个实际的URI解析器。 Depending on the answer, code from other answers can return 'null' instead of null , doesn't work with empty parameters ( ?foo=&bar=x ), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc. 根据答案,其他答案的代码可以返回'null'而不是null ,不能用空参数( ?foo=&bar=x ),不能一次解析并返回所有参数,重复工作如果你反复查询参数的URL等。

Use an actual URI parser, don't invent your own. 使用实际的URI解析器,不要发明自己的。

For those averse to jQuery, there's a version of the plugin that's pure JS . 对于那些厌恶jQuery的人来说,有一个纯JS的插件版本

If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this: 如果您不知道URL参数是什么,并希望获得具有参数中的键和值的对象,则可以使用以下命令:

function getParameters() {
  var searchString = window.location.search.substring(1),
      params = searchString.split("&"),
      hash = {};

  if (searchString == "") return {};
  for (var i = 0; i < params.length; i++) {
    var val = params[i].split("=");
    hash[unescape(val[0])] = unescape(val[1]);
  }
  return hash;
}

Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return: 使用/posts?date=9/10/11&author=nilbus等url调用getParameters()将返回:

{
  date:   '9/10/11',
  author: 'nilbus'
}

I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too: 我不会在这里包含代码,因为它甚至离问题更远,但weareon.net发布了一个库,它允许操作URL中的参数:

You can use the browser native location.search property: 您可以使用浏览器本机location.search属性:

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return unescape(val[1]);
    }
  }
  return null;
}

But there are some jQuery plugins that can help you: 但是有一些jQuery插件可以帮助你:

Based on the 999's answer : 基于999的答案

function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );  
}

Changes: 变化:

  • decodeURI() is replaced with decodeURIComponent() decodeURI()替换为decodeURIComponent()
  • [?|&] is added at the beginning of the regexp [?|&]在正则表达式的开头添加

Need to add the i parameter to make it case insensitive: 需要添加i参数以使其不区分大小写:

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
    );
  }
$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href); 
  return (results !== null) ? results[1] : 0;
}

$.urlParam("key");

For example , a function which returns value of any parameters variable. 例如,一个返回任何参数变量值的函数。

function GetURLParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

And this is how you can use this function assuming the URL is, 这就是假设URL是,你可以使用这个函数,

"http://example.com/?technology=jquery&blog=jquerybyexample". “http://example.com/?technology=jquery&blog=jquerybyexample”。

var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');

So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample". 所以在上面的代码变量中,“tech”将“jQuery”作为值,“blog”变量将是“jquerybyexample”。

You should not use jQuery for something like this! 你不应该使用jQuery这样的东西!
The modern way is to use small reusable modules through a package-manager like Bower. 现代的方法是通过像Bower这样的包管理器来使用小型可重用模块。

I've created a tiny module that can parse the query string into an object. 我创建了一个可以将查询字符串解析为对象的小模块 Use it like this: 像这样使用它:

// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå

After reading all of the answers I ended up with this version with + a second function to use parameters as flags 在阅读完所有答案后,我最终得到了这个版本+第二个函数,使用参数作为标志

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function isSetURLParameter(name) {
    return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}

There's a lot of buggy code here and regex solutions are very slow. 这里有很多错误代码,正则表达式解决方案非常慢。 I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple: 我找到了一个比正则表达式快20倍的解决方案,并且非常简单:

    /*
    *   @param      string      parameter to return the value of.
    *   @return     string      value of chosen parameter, if found.
    */
    function get_param(return_this)
    {
        return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.

        var url = window.location.href;                                   // Get the URL.
        var parameters = url.substring(url.indexOf("?") + 1).split("&");  // Split by "param=value".
        var params = [];                                                  // Array to store individual values.

        for(var i = 0; i < parameters.length; i++)
            if(parameters[i].search(return_this + "=") != -1)
                return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");

        return "Parameter not found";
    }

console.log(get_param("parameterName"));

Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. 正则表达式不是最重要的解决方案,对于这类问题,简单的字符串操作可以更有效地工作。 Code source . 代码来源

<script type="text/javascript">
function getURLParameter(name) {
        return decodeURIComponent(
            (location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
        );
    }

</script>

getURLParameter(id) or getURLParameter(Id) Works the same : ) getURLParameter(id)getURLParameter(Id)工作方式相同getURLParameter(Id)

jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts: jQuery代码片段,用于获取存储在url中的动态变量作为参数,并将它们存储为可随脚本使用的JavaScript变量:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}

example.com?param1=name&param2=&id=6

$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));  
//output: Gold%20Coast

console.log(decodeURIComponent($.urlParam('city'))); 
//output: Gold Coast

I created a simple function to get URL parameter in JavaScript from a URL like this: 我创建了一个简单的函数来从URL获取URL参数,如下所示:

.....58e/web/viewer.html?page=*17*&getinfo=33


function buildLinkb(param) {
    var val = document.URL;
    var url = val.substr(val.indexOf(param))  
    var n=parseInt(url.replace(param+"=",""));
    alert(n+1); 
}
buildLinkb("page");

OUTPUT: 18 输出: 18

Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash. 万一你们有像localhost / index.xsp这样的网址?a = 1#的东西,你需要得到的参数不是哈希。

var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        anchor = hash[1].split('#');
        vars.push(anchor[0]);
        vars[hash[0]] = anchor[0];
    }
}

Slight modification to the answer by @pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names. @pauloppenheim对答案的轻微修改,因为它不能正确处理可能是其他参数名称的一部分的参数名称。

Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value. 例如:如果您有“appenv”和“env”参数,则重新输入“env”的值可以获取“appenv”值。

Fix: 固定:

var urlParamVal = function (name) {
    var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
    return result ? decodeURIComponent(result[2]) : "";
};
function getURLParameters(paramName) 
{
        var sURL = window.document.URL.toString();  
    if (sURL.indexOf("?") > 0)
    {
       var arrParams = sURL.split("?");         
       var arrURLParams = arrParams[1].split("&");      
       var arrParamNames = new Array(arrURLParams.length);
       var arrParamValues = new Array(arrURLParams.length);     
       var i = 0;
       for (i=0;i<arrURLParams.length;i++)
       {
        var sParam =  arrURLParams[i].split("=");
        arrParamNames[i] = sParam[0];
        if (sParam[1] != "")
            arrParamValues[i] = unescape(sParam[1]);
        else
            arrParamValues[i] = "No Value";
       }

       for (i=0;i<arrURLParams.length;i++)
       {
                if(arrParamNames[i] == paramName){
            //alert("Param:"+arrParamValues[i]);
                return arrParamValues[i];
             }
       }
       return "No Parameters Found";
    }

}

This may help. 这可能有所帮助。

<script type="text/javascript">
    $(document).ready(function(){
        alert(getParameterByName("third"));
    });
    function getParameterByName(name){
        var url     = document.URL,
            count   = url.indexOf(name);
            sub     = url.substring(count);
            amper   = sub.indexOf("&"); 

        if(amper == "-1"){
            var param = sub.split("=");
            return param[1];
        }else{
            var param = sub.substr(0,amper).split("=");
            return param[1];
        }

    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM