使用 Prototype JavaScript 从当前 URL 获取 URL 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4467664/
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-10-25 13:46:56  来源:igfitidea点击:

get URL Parameters from current URL using Prototype JavaScript

javascripturlparametersprototypejs

提问by Sal Prima

I'm noob to JavaScript and want to use Prototype JSFramework to get some URL parameters. Imagine I have the following URL on my current browser:

我是 JavaScript 的菜鸟,想使用Prototype JS框架来获取一些 URL 参数。想象一下,我在当前浏览器上有以下 URL:

http://www.somewhere.com?param=abc

how can I get the value of 'param'using any function or utility of Prototype JS?

如何获得'param'使用Prototype JS 的任何功能或实用程序的价值?

回答by Scott

Prototype.js DOES provide a utility:

Prototype.js 确实提供了一个实用程序:

uri.toQueryParams();

回答by agamemnerd

Expanding on Scott's answer: to put the value of the URL variable 'param' into the javascript variable 'x' you would use Prototype like so:

扩展 Scott 的答案:要将 URL 变量 'param' 的值放入 javascript 变量 'x' 中,您可以像这样使用 Prototype:

x = document.URL.toQueryParams().param;

回答by Jacob Relkin

You really don't need Prototype for this:

你真的不需要原型:

function get_param(param) {
   var search = window.location.search.substring(1);
   var compareKeyValuePair = function(pair) {
      var key_value = pair.split('=');
      var decodedKey = decodeURIComponent(key_value[0]);
      var decodedValue = decodeURIComponent(key_value[1]);
      if(decodedKey == param) return decodedValue;
      return null;
   };

   var comparisonResult = null;

   if(search.indexOf('&') > -1) {
      var params = search.split('&');
      for(var i = 0; i < params.length; i++) {
         comparisonResult = compareKeyValuePair(params[i]); 
         if(comparisonResult !== null) {
            break;
         }
      }
   } else {
      comparisonResult = compareKeyValuePair(search);
   }

   return comparisonResult;
}

var param_value = get_param('param'); //abc