【问题标题】:Redirection Based on Query String基于查询字符串的重定向
【发布时间】:2018-08-18 15:36:53
【问题描述】:

不想膨胀一个包含 300 个条目的 .htaccess,我可以使用什么 javascript 根据对单个文件的请求中的查询字符串重定向到 URL。例如,

https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=57

我唯一关心的是 57 ,然后将其重定向到任何地方: https://www.anothercoolwebsite/secretworld/

在以下情况下,取 34 并重定向:

https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=34 https://www.anoldwebsite.com/cool/file.html

谢谢!

【问题讨论】:

  • 你想在哪里像id一样?
  • 首先查看window.location。您可以对此使用正则表达式模式匹配来获取您想要的参数,例如location.match(/LinkID=([0-9]+)/)
  • 是的,我在标签中引用了这个。 window.location 是首先想到的。我不确定如何将查询字符串合并到重定向的定义值中。

标签: javascript redirect query-string window.location


【解决方案1】:

这应该没问题。请记住,像 PHP 脚本这样的服务器端解决方案将适用于更多客户端。既然你提到了.htaccess,我想我应该让你知道fallback resource command

无论如何,这里是 JS 唯一的解决方案

function parseString(){//Parse query string
    var queryString=location.search.substring(1);//Remove ? mark

    var pair = queryString.split('&'); //Key value pairs

    var returnVal={};
    pair.forEach(function(item,i){
        var currPair = item.split('=');//Give name and value

        returnVal[currPair[0]]=currPair[1];
    });

    return returnVal;
}

var links=["index", "about"];//Sample array of links, make sure this matches up with your LinkID
location.href=links[parseString().LinkID]+".html"; //Redirect based on LinkID

【讨论】:

  • 谢谢你,本!不过,我对如何将多个 LinkID 与其相关 URL 相关联感到困惑。例如,我如何将 57 发送到 anothercoolwebsite/secretworld 和将 34 发送到 anoldwebsite.com/cool/file.html
  • @DavidTurner 在倒数第二行,我展示了一个数组,数组从零开始计数,因此“index”将为 LinkID=0,“about”为 1,等等
猜你喜欢
  • 1970-01-01
  • 2019-05-17
  • 2012-07-21
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多