简体   繁体   English

使用Javascript引用URL查询字符串参数

[英]Referring URL Query String Parameters w/ Javascript

I have a referring URL with a bunch of query string parameters. 我有一个带有许多查询字符串参数的引用URL。 Here's my code so far: 到目前为止,这是我的代码:

var refURL=document.referrer;
var stock=refURL.substring(refURL.indexOf('?')+7, refURL.length);

This worked fine when I only had 1 query string parameter at the end of my URL. 当我的URL末尾只有1个查询字符串参数时,此方法效果很好。 Now I have 3. I'd like to replace the second line so that the substring stops at the next "&". 现在我有了3。我想替换第二行,以便子字符串在下一个“&”处停止。

var stock=refURL.substring(refURL.indexOf('?')+7, ????);

From there, I'd like to have another line that captures the next parameter and stores it as a variable. 从那里,我想有另一行捕获下一个参数并将其存储为变量。 I can't use indexOf for that though, so how do I start from the "&" where I left off? 我不能为此使用indexOf,那么如何从中断的“&”开始呢?

Thanks! 谢谢!

There's much better ways to do query strings, so I'll discuss indexOf. 有很多更好的方法来执行查询字符串,所以我将讨论indexOf。 It actually takes a second optional parameter of fromIndex. 实际上,它使用fromIndex的第二个可选参数。

var str = "com/?test=0&i=2&me=3&u=56";
var prevIndx = str.indexOf('?');
var query = {}, arr, result, next;

while(prevIndx != -1) {
    next = str.indexOf('&', prevIndx+1);
    if (next == -1) next = str.length;
    result = str.substring(prevIndx+1, next);
    arr = result.split('=');
    console.log(prevIndx)    
    query[arr[0]] = arr[1];
    prevIndx = str.indexOf('&', prevIndx+1);
}

That code isn't pretty, but it demonstrates the fromIndex parameter of indexOf 该代码不是很漂亮,但是它演示了indexOf的fromIndex参数

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

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