【问题标题】:Passing a URL as a GET parameter in Javascript在 Javascript 中将 URL 作为 GET 参数传递
【发布时间】:2010-08-22 04:39:43
【问题描述】:

我正在尝试制作一个使用用户当前 URL 的书签,有点像使用此 javascript 代码的 tinyURL 书签

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

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

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

然后我使用:

$url=$_GET['url']; 

检索它。问题是,如果我在一个 url 中已经有一些获取样式信息的 url,它会搞砸一切。

例如,如果我在:

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

'_GET' 代码将 $url 设置为

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

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

【问题讨论】:

  • 你怎么剥离&hl=en&safe=off而不是um=1
  • @NullUserException: 我想这是因为 URL 中已经存在 ? 并且浏览器/服务器可能会将第二个视为“正常”字符。

标签: javascript url


【解决方案1】:

URL 具有指定的格式。 ? 之后的那部分,或者更准确地说是在?# 之间(如果存在),称为query string。它包含一个键值对列表——一个变量名、= 字符和值。变量用&分隔:

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

您应该转义location.href,因为它可以包含一些特殊字符,例如?&#

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

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

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

【讨论】:

  • 谢谢,看起来很简单。那么在 PHP 中解码的正确方法是什么?
  • 您不必这样做。 $_GET['url'] 将包含正确的值,即。 http://..../...html?abc=def&ghi=123。然而 PHP 就像 JavaScript 一样,带有几个用于 URL 转义的函数:urlencode()
  • @MikeD 我知道它有点老了,但我认为你应该接受这个答案:)
【解决方案2】:

试试

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

【讨论】:

    【解决方案3】:
    javascript:void(location.href='http://mywebsite.com/create.php?url='+encodeURIComponent(location.href))
    

    你需要转义字符。

    【讨论】:

      【解决方案4】:

      所以你想要什么,只是没有查询字符串的 url?

      $url = explode('?',$_GET['url']);
      $url = $url[0];
      

      【讨论】:

        【解决方案5】:

        像这样在 $_GET 参数中传递 url:

        http://yoursite.com/page.php?myurl=http://google.com/bla.php?sdsd=123&dsada=4323
        

        那么你需要使用encode函数:

        echo 'http://yoursite.com/page.php?url='.urlencode($mylink);
        
        //so, your output (url parameter) will get like this
        //http://yoursite.com/page.php?url=http%3A%2F%2Fgoogle.com%2Flink.php%3Fname%3Dsta%26car%3Dsaab
        

        之后,你需要解码参数:

        $variab = $_GET['url'];
        $variab = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($variab)); 
        $variab = html_entity_decode($variab,null,'UTF-8');
        echo $variab;
        

        这样,您可以将正确的链接作为参数传递。

        【讨论】:

          猜你喜欢
          • 2015-08-20
          • 2016-08-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-21
          • 1970-01-01
          相关资源
          最近更新 更多