douliu8327 2013-10-07 19:51
浏览 27
已采纳

1个表单,2个选择并在提交时将它们带到一个链接(PHP - 请帮助)

I would like to make a form with two selects ($a and $b) and a submit button which takes them to a link 'http://www.mywebsite.com/$a$b' when they click submit

for exemple if they chose in first select 'grade' and second '10' and then clicked submit it will take them to 'http://www.mywebsite.com/grade10'

That's my index.php , i didn't do it yet because i don't know how :P

    <?php 
error_reporting(E_ERROR | E_PARSE);

$a = $_POST['a'];
$b= $_POST['b'];
echo $a, $b;
?>
<form action="index.php" method="post">
<select name="a" title="a" id="a" >
    <option> </option>
    <option>a</option>
 </select>
 <select name="b" title="b" id="b" >
    <option> </option>
    <option>b</option>
 </select>
<input type="submit" value="submit" />
</form>

Thank you :)

  • 写回答

1条回答 默认 最新

  • dongyang1518 2013-10-07 19:59
    关注

    You don't technically need PHP for this, so you can cut out the middle-man of the POST request back to your server-side code and just go directly to the destination page via JavaScript. Maybe something like this:

    <form action="index.php" method="post" id="redirector">
        <select name="a" title="a" id="a" >
            <option> </option>
            <option>a</option>
        </select>
        <select name="b" title="b" id="b" >
            <option> </option>
            <option>b</option>
        </select>
        <input type="button" value="submit" />
    </form>
    
    <script type="text/javascript">
        document.getElementById('redirector').onsubmit = function () {
            var a = document.getElementById('a').value;
            var b = document.getElementById('b').value;
            window.location.href = 'http://www.mywebsite.com/' + a + b;
            return false;
        };
    </script>
    

    If they have JavaScript disabled, the form will still post back to the page, in which case the PHP code can still catch them and perform the redirect as well:

    $a = $_POST["a"];
    $b = $_POST["b"];
    header("Location: http://www.mywebsite.com/" . $a . $a);
    

    You'll probably want to add some error-checking logic to the values both in the JavaScript version and in the PHP version, in case users don't select something (if there's an empty option in the select, for example) or if a malicious user tries to post a bad value. Technically in the PHP version you're echoing back user input to the response, so you should look into things like cross-site scripting attacks and such. I'm not an expert on how to sanitize values like that in PHP, but it's worth researching.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题