表单输入数组 $_GET 逗号分隔在 URL 中

2022-01-04 00:00:00 arrays forms get php

我有一个表格:

<form action="results.php" method="get">
<select name="genres[]">
<option value="jazz"></option>
<option value="blues"></option>
<option value="rock"></option>
</select>
</form>

提交表单后,在 URL 中输入变为 example.com/?genres%5B%5D=jazz&genres%5B%5D=blues&genres%5B%5D=rock

After submitting the form, in the URL the input becomes example.com/?genres%5B%5D=jazz&genres%5B%5D=blues&genres%5B%5D=rock

此外,它看起来不太好,我的表单中有多个输入(大约 18 种类型),因此如果用户选择很多,URL 会变得很长.我希望它变成 /?genres=jazz,blues,rock

Next to that it doesn't look very nice, I have multiple inputs in my form (and around 18 genres) so if a user selects a lot, the URL becomes very long. I'd like it to become /?genres=jazz,blues,rock

现在我已经阅读了这篇文章,但是它没有说明如何制作更干净的 URL.接下来,我必须将输入用作数组,例如 $genres = $_GET['genres'] 以在另一个函数中使用.

Now I've read this post, but it doesn't state how to make the cleaner URL. Next to that, I have to use the input as an array, eg $genres = $_GET['genres'] to use in another function.

推荐答案

你可以这样做:

<!doctype html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

    <script>
        $(document).ready(function(){
           $("#go").click(function(){
               var g = $("#genres").val();
               var href = 'results.php?genres=';
               if(g != null) {
                   href += g;
               }
               document.location.href=href;
           });
        });
    </script>
</head>
<body>    
<select id="genres" size="3" multiple>
<option value="jazz">jazz</option>
<option value="blues">blues</option>
<option value="rock">rock</option>
</select>
<input type="button" value="go" name="submit" id="go">
</body>
</html>

在 results.php 中你应该:

in results.php you should:

$g = isset($_GET['genres'])?$_GET['genres']:"";
$genres = explode(",",$g);

我已经完全删除了表单,因为类型现在由 document.location.href 发送.jquery 的 .val() 函数返回预期的选定值(由 , 内爆)

i have removed the form completely because the genres are now sent by document.location.href. The .val() function of jquery returns the selected values like expected (imploded by ,)

相关文章