按名称或迭代的URL参数.. [英] URL parameters by name or iteration..

查看:56
本文介绍了按名称或迭代的URL参数..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些脚本来解析

URL参数,并列出它们或允许

按名称访问任何参数的值。

< http://www.physci.org/test/003url/index.html>

< http://www.physci.org/test/003url/index。 html?url = http://mybiz.com/& that = this& when = now#21>

< http://www.physci.org/test/003url/index。 html?url = http://mybiz.com/& when = now>


在我公开发布之前(并将其写入

进入任何数量的''开发套件''我通过我的网站提供

),我想通过了解Javascript的人来查看




此代码是否尽可能好?


这里列出了一些进一步的勘误和评论..

< ; http://www.physci.org/test/003url/index.html#errata>

页面中链接了3个脚本。

[..to省你拉起来的麻烦

来源并直接取。 ;-)]


欢迎所有评论。


-

Andrew Thompson
http://www.PhySci.org/ 开源软件套件
http://www.PhySci.org/codes/ Web& IT帮助
http://www.1point1C.org/ Science&技术

I have written a few scripts to parse the
URL arguments and either list them or allow
access to the value of any parameter by name.
<http://www.physci.org/test/003url/index.html>
<http://www.physci.org/test/003url/index.html?url=http://mybiz.com/&that=this&when=now#21>
<http://www.physci.org/test/003url/index.html?url=http://mybiz.com/&when=now>

Before I go offering it in public (and writing it
into any number of the ''development kits'' I deliver
through my site), I would like to get it reviewed
by the people who know Javascript.

Is this code as good as it can be?

Some further errata and comments are listed here..
<http://www.physci.org/test/003url/index.html#errata>
The 3 scripts are linked in the page.
[ ..to save you the trouble of pulling up
the source and making a direct fetch. ;-) ]

All comments welcome.

--
Andrew Thompson
http://www.PhySci.org/ Open-source software suite
http://www.PhySci.org/codes/ Web & IT Help
http://www.1point1C.org/ Science & Technology

推荐答案

* Andrew Thompson *写道:
*Andrew Thompson* wrote:
我写了几个脚本来解析
URL参数并列出它们或允许按名称访问任何参数的值。
....欢迎所有评论。
I have written a few scripts to parse the
URL arguments and either list them or allow
access to the value of any parameter by name. .... All comments welcome.




嗨安德鲁,我有类似的东西

www.andrewu.co.uk/tools/request/ ) - 它' '有点不同,因为它是试图成为ASP的Request.QueryString

集合的客户端版本。结果它有点膨胀,它可以重写(我似乎从来没有找到时间,但它真的需要它)。

它支持Count,Key和Item方法,因此您可以在使用它们之前查明是否存在

,它还可以处理多个键并具有

枚举通过''in''声明(警告适用)。


麻烦的是,我有点希望我没有写它,因为人们用它来支付
创建无法访问/无法访问的网站(例如,只有通过解码查询字符串客户端才能通过
工作的网站导航等)。该脚本采用

压缩格式在
http://www.andrewu.co .uk / tools / reque ... csjsrequest.js (未压缩的

版本通过电子邮件发送)。有一个交互式演示,您可以将
与服务器端原件进行比较 -
www.andrewu.co.uk/tools/request/demo/


Best,< br $> b $ b -

Andrew Urquhart

- 常见问题: www.jibbering.com/faq/

- 存档: www.google.com/groups?q=comp.lang.javascript

- 我的回复地址是无效,请使用: www.andrewu.co.uk/contact/



Hi Andrew, I''ve got something similar
(www.andrewu.co.uk/tools/request/) - it''s a little different as it''s
trying to be a client-side version of ASP''s Request.QueryString
collection. As a result it''s got a bit of bloat to it and it could do
with a re-write (I never seem to find the time, but it really needs it).
It supports Count, Key and Item methods so you can find out if keys
exist before using them, it also handles multiple keys and has
enumeration via the ''in'' statement (caveat applies).

Trouble is, I kind of wish I hadn''t written it because people use it to
create inaccessible/unusable web sites (e.g. site navigation that only
works by decoding the querystring client-side, etc.) The script is in a
compressed format at
http://www.andrewu.co.uk/tools/reque...csjsrequest.js (uncompressed
version upon emailing). There''s an interactive demo where you can
compare it against the server-side original -
www.andrewu.co.uk/tools/request/demo/.

Best,
--
Andrew Urquhart
- FAQ: www.jibbering.com/faq/
- Archive: www.google.com/groups?q=comp.lang.javascript
- My reply address is invalid, use: www.andrewu.co.uk/contact/


2004年5月8日星期六23:50:42 +0100,Andrew Urquhart写道:
On Sat, 8 May 2004 23:50:42 +0100, Andrew Urquhart wrote:
* Andrew Thompson *写道:
*Andrew Thompson* wrote:
我写了几个脚本来解析
URL参数和l ist他们或允许
按名称访问任何参数的值。 ......安德鲁,我有类似的东西
www.andrewu.co.uk/tools/request/ ) - 它有点不同
I have written a few scripts to parse the
URL arguments and either list them or allow
access to the value of any parameter by name. ...
Hi Andrew, I''ve got something similar
(www.andrewu.co.uk/tools/request/) - it''s a little different



< snip>


(笑)我怀疑如果我找了一半

小时我会找到(其中一个......)

预先存在的解决方案。


你的声音比我自己的小脚本听起来更全面

。 ;-)

麻烦的是,我有点希望我没有写它,因为人们用它来创建无法访问/无法使用的网站


<snip>

(chuckles) I suspected if I looked for an half
hour more I''d have found the (one of the..)
pre-existing solutions.

Yours sounds altogether more comprehensive
than my own little scripts. ;-)
Trouble is, I kind of wish I hadn''t written it because people use it to
create inaccessible/unusable web sites




Ahhhh。是。你做了一些漂亮的东西

和精彩的,提供额外的''额外''

特别神秘的情况*然后它

遭遇''人们'谁基于导航

系统,...,再也不会相同。 :-(


*我自己的兴趣源于配置

Java applets ..我有一个网站,我可以

生成服务器端的applet标签,但

我的大多数applet都可以使用URL提供的

参数进行增强,而且很多

在_their_网站上使用它们的人没有

PHP,JSP等。


当然,如果我的scirpts变成任何方式

众所周知,我不怀疑人们会用它做完b / b
完全愚蠢的事情..(耸耸肩)


感谢您的投入。:-)


-

Andrew Thompson
http://www.PhySci.org/ 开源软件套件
http://www.PhySci.org/codes/ Web& IT帮助
http://www.1point1C.org/ Science&技术



Ahhhh. Yes. You make something beautiful
and wonderful that provides that ''bit extra''
in particular arcane situations* and then it
encounters ''people'' who base a navigation
system on it, ..and is never the same again. :-(

* My own interest springs from configuring
Java applets.. I have a site where I can
generate applet tags on the server-side, but
most of my applets can be enhanced using
parameters provided by URL, and many of the
people who use them on _their_ sites have no
PHP, JSP etcetera.

Of course, if my scirpts become in any way
well known, I do not doubt people will do
completely stupid things with it.. (shrugs)

Thanks for your input. :-)

--
Andrew Thompson
http://www.PhySci.org/ Open-source software suite
http://www.PhySci.org/codes/ Web & IT Help
http://www.1point1C.org/ Science & Technology


Andrew Thompson写道:
Andrew Thompson wrote:
我编写了一些脚本来解析
URL参数并列出它们或允许
按名称访问任何参数的值。
< snip>在我公开发布之前(并将其写入我通过我的网站提供的任何数量的''开发套件'),我想通过它来审核
知道Javascript的人。

这段代码是不是很好?
I have written a few scripts to parse the
URL arguments and either list them or allow
access to the value of any parameter by name. <snip> Before I go offering it in public (and writing it
into any number of the ''development kits'' I deliver
through my site), I would like to get it reviewed
by the people who know Javascript.

Is this code as good as it can be?



< snip>


不,它最多是行人。


从您的 - QueryParameter开始 - 对象: -


| / **提供此URL参数的名称。 * /

| function getName(){

| return this.sName;

| }

|

| / **提供此URL参数的值。 * /

| function getValue(){

|返回this.sValue;

| }

|

| / **检查这是否是''paramName''URL参数。 * /

| function isParam(paramName){

| return(this.sName == paramName);

| }

|

| / **构造一个URL参数对象,并附加这些函数。 * /

|函数QueryParameter(paramName,paramValue){

| this.sName = paramName;

| this.sValue = paramValue;

|

| this.getName = getName;

| this.getValue = getValue;

| this.isParam = isParam;

| }


- 您正在创建4个全局函数来支持一个对象。通常,

代码对全局命名空间的影响应尽可能小。

对于全局可用的对象构造函数,影响不需要

不仅仅是构造函数名称。添加到

全局命名空间的项目越多,存在命名冲突的风险越大,并且b
导致意外的交互。


这在创建通用组件时最为重要(因为

似乎是您的意图)因为广义

组件的用户不应该与其实现密切相关

所以不应该关注自己避免命名

碰撞。您已选择创建名为getName的全局函数,

" getValue"和isParam,这是很好的自我解释名称,

但同样他们是可能适合其他地方的名字。

当这些名字它只是一种对象的属性然后它b / b
如果另一种类型的对象具有相同的属性名称无关紧要,

但是习惯性地将它们放在全局命名空间,你要求

麻烦(而那些只能雇用其他人的组件的人

将能够处理任何清单

后果)。


但是javascript构造函数有一个原型允许objets

用构造函数创建来继承公共属性,并且

允许定义这些属性,而不会对全局

命名空间产生任何影响。使用原型模式来定义你的对象

会导致: -


函数QueryParameter(paramName,paramValue){

this .sName = paramName;

this.sValue = paramValue;

}

QueryParameter.prototype.getName = function(){

返回this.sName;

};

QueryParameter.prototype.getValue = function(){

返回this.sValue;

};

QueryParameter.prototype.isParam = function(paramName){

return(this.sName == paramName);

};


使用构造函数自动创建的所有对象

获取原型上定义的所有方法,而无需

显式地将函数对象分配给对象属性,并且没有创建需要对全局

命名空间产生任何影响的方法。


但是这个命名空间问题会对系统的其他部分产生影响,

定义了另外3个函数和3个全局变量,其中2个只是暂时使用的b / b
似乎是执行角色

更适合功能局部变量。配置

也使用两个内联函数调用,如果没有

其他函数也不会工作,并且调用的函数不太适用于

其他情况(特别是当他们使用全局变量并且没有

参数时)。


我注意到,在网页上,你说; 我考虑按照Grant的建议将

对象添加到哈希(关联数组)中,但遗憾的是,
无法计算如何迭代元素。对我来说

利用javascript对象的哈希表方面是

存储名称/值对的明显方法。这样做允许命名属性

引用由本机代码而不是javascript处理,并且

特别是javascript循环。


你使用: -


| / **提供由''key''命名的参数的值。 * /

| function getQueryString(key){

| var value = null;

| for(var ii = 0; ii< parameters.length; ii ++){

| if(参数[ii] .isParam(key)){

| value = parameters [ii] .getValue();

|休息;

| }

| }

|返回值;

| } $ / $

- 循环(可能)所有创建的对象,

进行两次方法调用以确定返回哪个值,并且仍然是

只会返回与第一个名称/值对相对应的值

在查询字符串上遇到(一般方法应该能够

处理多个在查询字符串中出现相同的名称。


使用javascript对象存储名称/值对可以更有效地检索命名属性。迭代通过

使用的名称只是记录

可检索表格中使用的名称。


缺点使用javascript对象存储名称/值对

是他们有自己的一些属性(构造函数,toString)

当意图是需要时需要特别考虑创建

真正的通用代码。然后创建真正的通用代码i不是

一定是个好主意,因为所有代码实际上都会在特定的

上下文中使用,并且下载代码来处理永远不会发生的可能性。 b在特定情况下出现是浪费。例如一般查询

字符串接口可能会: -


/ *此函数调用创建一个名称值对的接口
$ b来自与当前页面的URL关联的查询字符串的$ b

在浏览器中。该接口可用作全局变量

调用 - queryStrings - 并有两种方法: -


queryStrings.getCountFor(name); - 返回在 - name下的查询字符串中找到的值的数量

- 作为参数提供,

或如果名称下不存在任何元素,则为数字零。 />

queryStrings.getValueFor(name,index); - 返回在

上找到的值 - 与 - name相关联的查询字符串 - 作为

第一个参数提供。第二个参数是可选的,表示

是为名称找到的值数组的索引。如果没有提供值,

索引默认为零。如果在索引下找不到值为
,或者名称下没有值,则返回
undefined。否则,为与

名称关联的查询字符串上提供的每个值返回一个字符串值,或者,如果在查询字符串上找不到名称,则返回
/>
相关值此方法返回布尔值true;


queryStrings.getNames(); - 返回对查询字符串中找到的所有名称的所有

的数组的引用。对阵列进行的任何修改

将持续存在并存在于稍后调用将返回
的数组中,但会改变名称值对

由其他方法返回。


* /

var queryStrings =(function(out){

var list = {};

var keyList = [];

var global = this;

var unsc =(global.decodeURIComponent)?'' decodeURIComponent'':

''unescape'';

var nameSafe = ['''','''']; //第一个元素是空格字符

函数addItem(name,value){

nameSafe [1] = name;

var sName = nameSafe.join('''') ;

if(list [sName]){

list [sName] [out [sName] .length] = value;

} else {

list [sName] = [value];

keyList [keyList.length] = name;

}

}

if(typeof location!=''undefined''){

var nvp,ofSet,temp = location .search || location.href ||'''';

if((ofSet = temp.indexOf(''?''))> -1){

temp = temp.split("#")[0];

temp = temp.substring((ofSet + 1),temp。 ();($ c $; br />
nvp = workAr [c] .split(''='');

if(nvp.length> 1){

addItem (global [unsc](nvp [0]),global [unsc](nvp [1]));

} else if(nvp.length == 1){

addItem(global [unsc](nvp [0]),true);

}

}

}

}

返回({

getCountFor:函数(名称){

nameSafe [1] = name;

var sName = nameSafe.join('''');

return((list [sName]&& list [sName] .length)| 0);

},

getValueFor:function(name,index){

nameSafe [1] = name;

var sName = nameSafe .join('''');

if(list [sName]){

返回列表[sName] [(index | 0)];

} //否则返回undefined(默认情况下)

},

getNames :function(){

返回keyList;

}

});

})(); //内联函数表达式调用。


- 并涵盖查询字符串使用中的大多数可能性。但是在一个真实的

情况下,有可能避免查询字符串中的名称

与javascript对象属性重合,知道名称/值

对将是不同的,知道名称将始终伴随

值,知道预期使用哪些值并避免名称和

值将被修改用URL编码。


知道这些东西可以使用更简单的代码,但仍然可以实现预期的结果。例如: -


var queryStrings =(function(out){

if(typeof location!=''undefined''){

var temp = location.search || location.href ||'''';

var nvp,ofSet;

if((ofSet = temp.indexOf (''?''))> -1){

temp = temp.split("#")[0];

temp = temp。 substring((ofSet + 1),temp.length);

var workAr = temp.split(''&'');

for(var c = workAr .length; c - ;){

nvp = workAr [c] .split(''='');

if(nvp.length> 1) {

out [nvp [0]] = nvp [1];

}

}

}

}

退出;

}({})); //内联函数表达式调用传递了一个对象

//文字 - {} - 作为参数(out)。

我注意到你的页面包含了这一行; 它旨在通过告诉用户他们需要这个页面的JS来降低

''优雅''。

不是优雅退化的定义。我会认识到它(

从来没有''优雅''用这种细节困扰用户)。

虽然这不是真正的角色一个低级别的组件,以便优雅地降低自己的价值。对于希望使用它的代码来说,这是一项任务;决定它将如何响应无法提取查询需要/期望的信息。

对组件设计者的责任只是为了确保

代码在失败时实际上不会出错。并且在发生故障时有明确定义的

行为,在这种情况下,可能只需要

,在请求时不返回值

按名称。


Richard。


<snip>

No, it is pedestrian at best.

Starting with your - QueryParameter - object:-

| /** Provide the name of this URL parameter. */
| function getName() {
| return this.sName;
| }
|
| /** Provide the value of this URL parameter. */
| function getValue() {
| return this.sValue;
| }
|
| /** Check if this is the ''paramName'' URL parameter. */
| function isParam( paramName ) {
| return ( this.sName==paramName );
| }
|
| /** Construct an URL parameter object, and attach the functions. */
| function QueryParameter( paramName, paramValue ) {
| this.sName = paramName;
| this.sValue = paramValue;
|
| this.getName = getName;
| this.getValue = getValue;
| this.isParam = isParam;
| }

- you are creating 4 global function to support one object. Generally,
code should have as little impact on the global namespace as possible.
For a globally available object constructor that impact does not need to
be more than just the constructor name. The more items added to the
global namespace the more there is a risk of naming collisions and
resulting unexpected interactions.

This is of most significance when creating generalised components (as
appears to be your intention) because the users of a generalised
component should not be expected to be intimate with its implementation
and so should not need to concern themselves with avoiding naming
collisions. You have chosen to create global functions called "getName",
"getValue" and "isParam", which are nice self-explanatory names to use,
but equally they are names that are likely to be well suited elsewhere.
When the those names are just the properties of a type of object then it
doesn''t matter if another type of object has the same property names,
but habitually place them in the global namespace and you are asking for
trouble (and individuals who can only employ other people''s components
are going to be the least capable of handling any manifest
consequences).

But javascript constructors to have a prototype which allows objets
created with the constructor to inherit common properties, and also
allows those properties to be define without any impact on the global
namespace. Using the prototype pattern to define your object would
result in:-

function QueryParameter(paramName, paramValue){
this.sName = paramName;
this.sValue = paramValue;
}
QueryParameter.prototype.getName = function(){
return this.sName;
};
QueryParameter.prototype.getValue = function(){
return this.sValue;
};
QueryParameter.prototype.isParam = function(paramName){
return (this.sName==paramName);
};

With which all objects created with the constructor automatically
acquire all of the methods defined on the prototype without any need to
explicitly assign function object to object properties, and without the
creation of the methods needing to have any impact on the global
namespace.

But this namespace problem caries over in to the rest of the system,
which defines another 3 functions and 3 global variables, 2 of which are
only temporarily used and so would seem to be performing roles that
would be better suited to function local variables. The configuration
also uses two inline function calls, neither will work without the
other, and the functions being called are unlikely to be applicable in
other situations (especially as they employ global variables and have no
parameters).

I notice that, on the web page, you say; "I considered adding the
objects to a hash (associative array) as suggested by Grant , but
unfortunately could not then figure how to iterate the elements. For me
exploiting the hashtable-like aspects of javascript objects is the
obvious way to store name/value pairs. Doing so allows named property
references to be handled by native code instead of javascript, and
particularly javascript loops.

You use:-

| /** Provides the value for the parameter named by ''key''. */
| function getQueryString(key) {
| var value = null;
| for (var ii=0; ii<parameters.length; ii++) {
| if ( parameters[ii].isParam(key) ) {
| value = parameters[ii].getValue();
| break;
| }
| }
| return value;
| }

- which loops through (potentially) all of the created objects, and
makes two method calls to determine which value to return, and still
will only return the value corresponding with the first name/value pair
encountered on the query string (a general method should be able to
handle multiple occurrences of the same name in the query string.

Using javascript object to store name/value pairs allows much more
efficient retrieval of named properties. Being able to iterate through
the names used is just a matter of recording the names used in a
retrievable form.

The drawback with using a javascript objects to store name/value pairs
is that they have some properties of their own (constructor, toString)
which need some special consideration when the intention is to create
truly general code. But then creating truly general code is not
necessarily a good idea as all code will actually be used in a specific
context, and downloading code to handle possibilities that will never
arise in the specific situation is wasteful. For example a general query
string interface might go:-

/* This function call creates an interface to the name value pairs
from the query string associated with the URL of the current page
in the browsers. The interface is available as a global variable
called - queryStrings - and has two methods:-

queryStrings.getCountFor(name); - Returns the number of values found
in the query string under the - name - provided as a parameter,
or numeric zero if no elements exist under the name.

queryStrings.getValueFor(name, index); - Returns the value found on
the query string associated with the - name - provided as the
first parameter. The second parameter is optional and represents
an index into an array of the values found for the name. The
index defaults to zero if no value is provided. If no value is
found under the index, or no values exist under the name, then
undefined is returned. Otherwise a string value is returned for
each value provided on the query string associated with the
name, or, if a name was found on the query string with no
associated value this method returns boolean true;

queryStrings.getNames(); - Returns a reference to an Array of all
of the names found on the query string. Any modifications made
to the array will persist and be present in the Array that will
be returned by later calls, but will alter the name value pairs
returned by the other methods.

*/
var queryStrings = (function(out){
var list = {};
var keyList = [];
var global = this;
var unsc = (global.decodeURIComponent)?''decodeURIComponent'':
''unescape'';
var nameSafe = ['' '','''']; //first element is the space character
function addItem(name, value){
nameSafe[1] = name;
var sName = nameSafe.join('''');
if(list[sName]){
list[sName][out[sName].length] = value;
}else{
list[sName] = [value];
keyList[keyList.length] = name;
}
}
if(typeof location != ''undefined''){
var nvp,ofSet, temp = location.search||location.href||'''';
if((ofSet = temp.indexOf(''?'')) > -1){
temp = temp.split("#")[0];
temp = temp.substring((ofSet+1), temp.length);
var workAr = temp.split(''&'');
for(var c = workAr.length;c--;){
nvp = workAr[c].split(''='');
if(nvp.length > 1){
addItem(global[unsc](nvp[0]),global[unsc](nvp[1]));
}else if(nvp.length == 1){
addItem(global[unsc](nvp[0]), true);
}
}
}
}
return ({
getCountFor:function(name){
nameSafe[1] = name;
var sName = nameSafe.join('''');
return ((list[sName] && list[sName].length)|0);
},
getValueFor:function(name, index){
nameSafe[1] = name;
var sName = nameSafe.join('''');
if(list[sName]){
return list[sName][(index|0)];
} //else return undefined (by default)
},
getNames:function(){
return keyList;
}
});
})(); //inline function expression call.

- and cover most possibilities in query string use. But in a real
situation it would be possible to avoid names in the query string that
would coincide with javascript object properties, know that name/value
pairs would be distinct, know that names would always have accompanying
values, know which values where expected to be used and avoid names and
values that would be modified in URL encoding.

Knowing these things allows much simpler code to be used, but to still
achieve the desired results. e.g.:-

var queryStrings = (function(out){
if(typeof location != ''undefined''){
var temp = location.search||location.href||'''';
var nvp, ofSet;
if((ofSet = temp.indexOf(''?'')) > -1){
temp = temp.split("#")[0];
temp = temp.substring((ofSet+1), temp.length);
var workAr = temp.split(''&'');
for(var c = workAr.length;c--;){
nvp = workAr[c].split(''='');
if(nvp.length > 1){
out[nvp[0]] = nvp[1];
}
}
}
}
return out;
}({})); //inline function expression call passed an object
// literal - {} - as its parameter (out).
I notice your page includes the line; "It is designed to degrade
''gracefully'' by telling the user they require JS for this page.". That
is not a definition of "graceful degradation" that I would recognise (it
is never ''graceful'' to be bothering the user with this sort of detail).
Though it is not really the role of such a low-level component to
gracefully degrade itself. That is a task for the code that wishes to
use it; to decide how it is going to respond to not being able to
extract the query sting information that it requires/expects. The
responsibility for the component designer is only to ensure that the
code does not actually error when it fails. and to have well defined
behaviour when that failure occurs, for which it is probably only
necessary, in this context, not to return values when they are requested
by name.

Richard.


这篇关于按名称或迭代的URL参数..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆