在Javascript中将URL作为GET参数传递 [英] Passing a URL as a GET parameter in Javascript

查看:60
本文介绍了在Javascript中将URL作为GET参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个使用用户当前网址的书签,类似于使用此javascript代码的tinyURL书签

I am trying to make a bookmarklet that uses the user's current URL, kind of like the tinyURL bookmarklet that uses this javascript code

javascript:void(location.href='http://tinyurl.com/create.php?url='+location.href)

所以我复制了同样的东西并制作了

So I copied that same thing and made

javascript:void(location.href='http://mywebsite.com/create.php?url='+location.href)

然后我使用:

$url=$_GET['url']; 

来检索它。问题是,如果我在网址上已经有一些获取样式信息的网址,它就会混淆一切。

to retrieve it. The problem is, if I am on a url that already has some get style info in the url, it messes everything up.

示例,如果我在:

http://www.google.ca/webhp?um=1&hl=en&safe=off

'_GET'代码将$ url设为

The '_GET' code sets $url to be

http://www.google.ca/webhp?um=1

所以我认为google URL中的信息搞乱了我的所有URL解析,我想我做的事情非常不正确,或者有人有一个非常优雅的解决方案。我该怎么办?请帮助

So I think the info in google URL is messing up all of my URL parsing, I imagine I am doing something very incorrectly or someone has a very elegant solution for this. What should I do? please help

推荐答案

网址具有指定的格式。那个部分在之后,或更准确地介于如果存在,则称为查询字符串。它包含一个键值对列表 - 变量名称, = 字符和值。变量由& 分隔:

URL has a specified format. That part after ?, or to be more exactly between ? and # if exists, is called query string. It contains a list of key-value pairs - a variable name, = character and the value. Variables are separated by &:

key1=value1&key2=value2&key3=value3&key4=value4

你应该逃避 location.href 因为可以包含一些特殊字符,例如&

You should escape location.href as it can contains some special characters like ?, & or #.

要在JavaScript中转义字符串,请使用 encodeURIComponent() 函数如下:

To escape string in JavaScript use encodeURIComponent() function like so:

location.href = "http://tinyurl.com/create.php?url=" + encodeURIComponent(location.href)

它会将& 等字符替换为 26%。该字符序列不被视为变量分隔符,因此它将作为变量的值附加。

It will replace characters like & into %26. That sequence of characters isn't treated as a variable separator so it will be attached as a variable's value.

这篇关于在Javascript中将URL作为GET参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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