Javascript Url 参数解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10609511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:06:58  来源:igfitidea点击:

Javascript Url Parameter parsing

javascripthtmlurl

提问by Spartacus

So, I really need some help. I've done extensive searches, and some of the solutions I've found are great but aren't working for me, so here goes...

所以,我真的需要一些帮助。我已经进行了广泛的搜索,我发现的一些解决方案很好,但对我不起作用,所以这里是......

When someone comes to my site, they are going to click on a link which will pass a URL to "recipes.html"... For Example, if they clicked on "Ancho Chile Sauce", the URL would be:

当有人访问我的网站时,他们会点击一个链接,该链接会将 URL 传递给“recipes.html”……例如,如果他们点击“Ancho Chile Sauce”,则 URL 将是:

blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce

blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce

This parameter is actually the name of a JPEG in the folder "Recipes", of course with the ".jpg" extension

这个参数其实就是“Recipes”文件夹中一个JPEG的名字,当然还有“.jpg”扩展名

I need to take this parameter into a string and add "Recipes/" before it and ".jpg" after it, and then alter the source of an image tag in my html document to display the new dynamically called recipe image.

我需要将此参数放入一个字符串中,并在它之前添加“Recipes/”和“.jpg”,然后在我的 html 文档中更改图像标签的来源以显示新的动态调用的配方图像。

I thought I'd done this, but nothing seems to be working. There's obviously something I'm doing wrong in my Javascript, because my markup works fine and the url with parameter is getting passed.

我以为我已经这样做了,但似乎没有任何效果。显然我在我的 Javascript 中做错了一些事情,因为我的标记工作正常并且带有参数的 url 正在传递。

Here is my code:

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<title>Recipes</title>
<link href="mobi-styles.css" rel="stylesheet" />
<script type="text/javascript">
function getParam ( sname )
{
  var params = location.search.substr(location.search.indexOf("?")+1);
  var sval = "";
  params = params.split("&");
    // split param and value into individual pieces
    for (var i=0; i<params.length; i++)
       {
         temp = params[i].split("=");
         if ( [temp[0]] == sname ) { sval = temp[1]; }
       }
  return sval;
}
window.onload = changePic();
var param = getParam("r");
var recipeName = "Recipes/"+param+".jpg";
function changePic() {
document.getElementById("recipe").src=recipeName;
}
</script>
</head>

<body>
<img class"resizer" id="recipe" src="" />
</body>
</html>

Please help! Me love you long time!

请帮忙!我爱你很久了!

回答by Joseph

remove the (). When attaching events, you assign a function, not the result of a function call. What you did was call changePic(), returned svaland assigned the value of svalto window.onload- that's wrong.

删除(). 附加事件时,您分配一个函数,而不是函数调用的结果。你所做的是 call changePic(),返回sval并分配svalto的值window.onload- 这是错误的。

window.onload = changePic;
                         ^---remove ()

And move window.onload = changePicat the bottom so JSLint won't be mad. It's best practice to declare functions up top before using them, even when there is hoisting.

window.onload = changePic在底部移动,这样 JSLint 就不会生气。最好的做法是在使用函数之前将函数声明在顶部,即使存在提升也是如此。

回答by Ibu

I have written a little script that gives me access to the url paramater in the past and it can be very effective. it runs in the beginning of the file so you can access them anytime.

过去我写了一个小脚本,让我可以访问 url 参数,它非常有效。它在文件的开头运行,因此您可以随时访问它们。

GET = (function () {
    var get = {
        push:function (key,value){
            var cur = this[key];
            if (cur.isArray){
                this[key].push(value);
            }else {
                this[key] = [];
                this[key].push(cur);
                this[key].push(value);
            }
        }
    },
    search = document.location.search,
    decode = function (s,boo) {
        var a = decodeURIComponent(s.split("+").join(" "));
        return boo? a.replace(/\s+/g,''):a;
    };
    search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function (a,b,c) {
        if (get[decode(b,true)]){
            get.push(decode(b,true),decode(c));
        }else {
            get[decode(b,true)] = decode(c);
        }
    });
    return get;
})();

Now you can access the parameters you want:

现在您可以访问所需的参数:

blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce

GET['r']; // will print: Ancho-Chile-Sauce

or

或者

GET.r; 

if the parameter are repeated multiple times then it is stored as an array;

如果参数重复多次,则将其存储为数组;

example.com/test?name=John&name=Smith

the name property becomes an array

name 属性变成了一个数组

GET.name[1] ; // Smith

I hope this can help you

我希望这可以帮助你

回答by robrich

Change this:

改变这个:

if ( [temp[0]] == sname ) { sval = temp[1]; }

To this:

对此:

if ( temp[0] == sname ) { sval = temp[1]; }

回答by Zuul

This is what I use to collect URL variables:

这是我用来收集 URL 变量的内容:

JQUERY EXTENSION

查询扩展

$.extend({
  getUrlVars: function(){
    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;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

And you can use it like this:

你可以像这样使用它:

// blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce

var r = $.getUrlVar('r');

alert(r); // outputs 'Ancho-Chile-Sauce'

function changePic() {
  $('#recipe').attr("src", r);
}


If you don't use Jquery, a Javascript onlysolution would be:

如果您不使用 Jquery,则使用Javascript 的解决方案是:

function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

And can be used like this:

并且可以这样使用:

var r = getQueryVariable("r");

alert(r); // outputs 'Ancho-Chile-Sauce'

function changePic() {
  document.getElementById("recipe").src = r;
}

回答by philbv

parseURLparameters(string) {
    let parsed = {};
    (string.split('?')[1] || string).split('&')
                                    .map((item) => {
                                        return item.split('=');
                                    })
                                    .forEach((item) => {
                                        parsed[item[0]] = item[1];
                                    });
    return parsed;
}

So you can pass an any string:

所以你可以传递一个任何字符串:

'?asd'
'?asd=123'
'asd=&kjnwer=13'

and so on...

等等...