【问题标题】:Redirect in javascript: IF GET parameter key allow to stay on the page; otherwise redirect to another pagejavascript中的重定向:IF GET参数键允许停留在页面上;否则重定向到另一个页面
【发布时间】:2018-04-29 09:38:45
【问题描述】:

编写此代码的最佳方法是什么?我们想让知道如何添加 ?Redirect=No 以附加 url 的人留在页面上并查看它,否则该人将被重定向到新站点或“我们已移动”页面。一个示例将非常有助于我了解如何检测 GET url 用例。我是一个菜鸟 javascript 编码器,因此非常感谢您的帮助!

选项#1

  • 用例 1: oldsite.mysite.com:重定向到新站点用例
  • 用例 2: oldsite.mysite.com?Redirect=No :不重定向,页面加载正常

选项 #2(更用户友好的方法)

  • 用例 1: oldsite.mysite.com:站点立即重定向到新站点 网站

  • 用例 2: oldsite.mysite.com?Redirect=No :不重定向并且 页面加载正常

  • 用例 3: oldsite.mysite.com/AnyOtherPage :重定向到“我们已经 移动页面”,然后在“x”秒后重定向到新站点。

  • 用例 4: oldsite.mysite.com/AnyOtherPage?Redirect=No : 不 重定向,页面正常加载


<script>

// Check if the GET url parameter of "redirect=NO" is appended to the url 
and redirect if there is no parameter defined.


$(function() {


  if (  ... //url equals oldsite.mysite.com ...  )

      //GET redirect=NO so do nothing and stay here

      window.location.href = "https://newsite.mysite.com";

     }



   else if ( ... //url equals oldsite.mysite.com/anyOtherPage ...  )

     //GET redirect=NO so do nothing and stay here

     window.location.href = "https://oldsite.mysite.com/we-have-moved";

  }

 });

</script>

或者它看起来更像这样?

<script>

switch(expression) {

    case n:
         //GET url contains parameter "Redirect=NO"
         break;

    case n:
         if (//url contains a child page name) {

          window.location.href = "https://newsite.mysite.com/we-have-moved";

             }

         break;

   default:
         window.location.href = "https://newsite.mysite.com"; 

 }

</script>

【问题讨论】:

    标签: javascript if-statement url redirect switch-statement


    【解决方案1】:

    在实际代码中取消注释。

    var sleep =(ms)=> new Promise((res, rej)=>{
             setTimeout( res, ms );
    });
    var redirect = async (pathname, ms) => {
        if(ms){ 
           await sleep(ms);
           console.log('waiting for' + ms + '...');
        }else{
          console.log('immediate');
        }
        
        console.log('http://newUrl.com' + pathname);//location.href = 'http://newUrl.com' + pathname 
    }
    
    var main = (url, ms) => {
      var u =new URL(url);
      var sp = Array.from(u.searchParams.entries());
      sp.some((arr,i)=>arr[0] === 'Redirect' && arr[1]=== 'No')? '': u.pathname === '/' ? redirect(''+u.search,0) : redirect(u.pathname+u.search, ms);
    }
    
    
    
    
    main('http://oldsite.mysite.com?Redirect=No', 5000);
    main('http://oldsite.mysite.com/AnyOtherPage?Redirect=No', 5000);
    
    console.log('redirection cases');
    main('http://oldsite.mysite.com/AnyOtherPage', 5000);
    main('http://oldsite.mysite.com', 5000);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      相关资源
      最近更新 更多