PHP从多个选定值生成表单操作URL。 (没有Javascript)

时间:2014-11-28 23:48:04

标签: php forms url select

我正在尝试为汽车网站制作搜索表单,我需要使用所选值生成表单操作。例如:

<form metho="" action="">
<select id="make" name="make" class="select">
<option value="honda">honda</option>
<option value="ford">ford</option>
</select>

<select id="model" name="model" class="select">
<option value="civic">civic</option>
<option value="fit">fit</option>
</select>

<select id="year" name="year" class="select">
<option value="2014">2014</option>
<option value="2013">2013</option>
</select>

<input type="submit" value="Submit">
</form>

因此,如果我选择Honda,civic,2014,行动将改为: action =“mydomain.com/honda/civic/2014”

我发现了这个,但是在javascript中,我不知道如何在PHP中使用它:

$("#gender, #age").on('change', function() {
    var gender = $("#gender").val(),
        age = $("#age").val(),
        site = "somepage.php#"+gender+"-"+age; //inconsistent use of -/_

        $("form").attr("action", site)};
    }); 
});

我是个乞丐,所以提前抱歉。

2 个答案:

答案 0 :(得分:2)

正如上面的评论所述,您不能通过PHP的使用来更改action=""。客户端脚本执行此操作,或者,您可以先提交表单。在同一页面上收集值/输入,然后在处理表单后使用header()函数:

<?php
// if its submitted
if(isset($_POST['make'], $_POST['model'], $_POST['year'])) {
    // gather all the values
    $make = urlencode($_POST['make']);
    $model = urlencode($_POST['model']);
    $year = $_POST['year'];
    // make a header redirect
    header("Location: http://www.exampledomain.com/$make/$model/$year");
    exit;
}

?>

<form method="POST" action=""> <!-- leave the action="" empty -->
    <select id="make" name="make" class="select">
        <option value="honda">honda</option>
        <option value="ford">ford</option>
    </select>

    <select id="model" name="model" class="select">
        <option value="civic">civic</option>
        <option value="fit">fit</option>
    </select>

    <select id="year" name="year" class="select">
        <option value="2014">2014</option>
        <option value="2013">2013</option>
    </select>

    <input type="submit" value="Submit">
</form>

答案 1 :(得分:0)

您可以尝试以下内容:

<?php
if ((isset($_POST['make'])) and (isset($_POST['model'])) and (isset($_POST['year']))) {
    $url = "mydomain.com/".$_POST['make']."/".$_POST['model']."/".$_POST['year']; //with http://
    header("Location: ".$url);
    die();
}
?>

<form method="POST" action="">
<select id="make" name="make" class="select">
<option value="honda">honda</option>
<option value="ford">ford</option>
</select>

<select id="model" name="model" class="select">
<option value="civic">civic</option>
<option value="fit">fit</option>
</select>

<select id="year" name="year" class="select">
<option value="2014">2014</option>
<option value="2013">2013</option>
</select>

<input type="submit" value="Submit">
</form>

但这不是最好的方法。