简体   繁体   English

基于URL位置的jQuery重定向

[英]Jquery Redirect Based on URL location

This is what I'm trying to solve for... 这就是我要解决的问题...

  1. Only if the URL explicitly contains /foldername/index.htm && /foldername/ on mydomain.com then redirect to http://www.example.com 仅当URL在mydomain.com上显式包含/foldername/index.htm && / foldername /时,才重定向到http://www.example.com
  2. Should the URL contain any URL parameter /foldername/index.htm?example it should not redirect URL是否应包含任何 URL参数/foldername/index.htm?例如,不应重定向
  3. All other URLs should not redirect 其他所有网址均不应重定向

This is my javascript which is incomplete, but is ultimately what I'm trying to solve for... 这是我的不完整的javascript,但最终是我要解决的问题...

var locaz=""+window.location;
if (locaz.indexOf("mydomain.com") >= 0) {
    var relLoc = [
        ["/foldername/index.htm"],
        ["/foldername/"]
    ];
    window.location = "http://www.example.com"; 
}

This is for the purpose to manage a URL that some users are hitting based on a particular way like a bookmark. 这是为了管理基于某些特定方式(例如书签)的某些用户正在访问的URL。 Without removing the page, we want to monitor how many people are hitting the page before we take further action. 在不删除页面的情况下,我们希望在采取进一步措施之前监视有多少人点击该页面。

Won't the page always be on the same domain, also if the url contains /foldername/pagename.htm won't it also already include /foldername ? 页面不会始终位于同一域中,如果URL包含/foldername/pagename.htm它是否也已经包含/foldername吗? So an && check there would be redundant. 因此, &&检查将是多余的。

Try the below code. 试试下面的代码。

var path = window.location.pathname;

if  ( (path === '/foldername' || path === '/foldername/index.html') && !window.location.search ) {
    alert('should redirect');
} else {
    alert('should not redirect');
}
var url = window.location;
var regexDomain = /mydomain\.com\/[a-zA-Z0-9_\-]*\/[a-zA-Z0-9_\-]*[\/\.a-z]*$/    
if(regexDomain.test(url)) { 
  window.location = "http://www.example.com"; 
}

Familiarize with the location object. 熟悉位置对象。 It provides pathname , search and hostname as attributes, sparing you the RegExp hassle (you'd most like get wrong anyways). 它提供pathnamesearchhostname作为属性,从而避免了RegExp的麻烦(无论如何,您最想出错 )。 You're looking for something along the lines of: 您正在寻找以下方面的东西:

// no redirect if there is a query string
var redirect = !window.location.search 
  // only redirect if this is run on mydomain.com or on of its sub-domains
  && window.location.hostname.match(/(?:^|\.)mydomain\.com$/)
  // only redirect if path is /foldername/ or /foldername/index.html
  && (window.location.pathname === '/foldername/' || window.location.pathname === '/foldername/index.html');

if (redirect) {
  alert('boom');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM