如何根据表单选择重定向人员

How to redirect people depending on form selection

本文关键字:重定向 选择 表单 何根      更新时间:2023-09-26

使用一个简单的html表单,如何根据用户的选择重定向用户?

<form id="contact-form" action="xxxxx" method="post">
<li>option1
<ul>
  <li><label>Red</label> <input type="radio" name="Option1" id="vsat" value="red"></li>
  <li><label>Blue</label> <input type="radio" name="Option1" id="blue" value="blue"></li>
  <li><label>White</label> <input type="radio" name="Option1" id="white" value="white"></li>
</ul>
</li>
<li>option2
<ul>
  <li><label>Big</label> <input type="radio" name="Option2" id="vsat" value="red"></li>
  <li><label>Small</label> <input type="radio" name="Option2" id="blue" value="blue"></li>
</ul>
</li>
<li>Location
<ul>
  <li><label>Europe</label> <input type="radio" name="Option3" id="eur" value="eur">    </li>
<li><label>America</label> <input type="radio" name="Option3" id="ame" value="ame"></li>
</ul>

  • 例如:

    如果选择为:红色/大/欧洲,请访问www.somedomain.com/001

    如果选择为:蓝色/大/欧洲,请访问www.somedomain.com/006

    如果选择为:blue/small/America,请访问www.somedomain.com/us/03

    谢谢你们的帮助!

    首先,您将使用某种重定向脚本,我将在此处通过标头使用。

    <?php
       //this will NOT work, the browser received the HTML tag before the script or even a white space
       header( 'Location: http://www.linktoredirect.com/' ) ;
    ?>
    

    然后你应该让所有的选项都感觉像一个,这样你就可以在开关或类似的东西中使用它。

    <?php
    $singleOption = $_GET['option1']."-".$_GET['option2']."-".$_GET['option3'];
    //Now that you have one big option you can easily do:
    switch($singleOption){
        case "red-big-europe": $sufix = '001'; break;
        case "blue-big-europe": $sufix = '002'; break;
        //And so on
        default: $sufix='404'; //some default value to redirect if it doesn't match anything
    }
    //With the switch you already have the sufix, so you only do:
    header( 'Location: http://www.somedomain.com/$sufix' ) ;
    ?>
    

    //编辑

    请注意,我还没有对数据进行净化或验证。当数据来自用户时,您应该始终保持数据的清洁和检查。希望它能有所帮助;)

    您可以向表单添加onSubmit处理程序,检查表单值,并使用Javascript重定向到所需页面。如果你想让它在没有Javascript的情况下工作,你的PHP脚本基本上可以做同样的事情,方法是将HTTP Location:标头设置为你想要访问的URL

    我会使用jQueryhttp://jquery.com/

    我会在每个输入中添加一个类,即选项,并在每个包含你想要指向的url的输入中添加数据属性

    <input type="hidden" name="location" id="location" />
    

    然后是这样的:

    $(function() {
       $('.options').each(function() {
          $(this).click(function() {
             if($(this).is(':checked')) {
               var loc = $(this).attribute('data-location');
               $('#location').val(loc);
             }
           }
       }
    });
    

    然后在提交时

     $('#formID').submit(function() {
        var loc = $('#location').val(); 
        window.location = loc;
     });
    

    这样就可以循环使用类"options"的所有单选按钮,并为它们的单击添加一个事件侦听器。因此,当有人点击一个时,它会检查它是否被选中(因为它可能被点击以取消选择),如果它被选中,那么它会将与该选择相关的url(存储在数据位置属性中)添加到#位置隐藏输入中。然后,当表单提交时,它会将用户发送到该url,您需要添加一些内容来处理空url等。