Form input array $_GET comma separated in URL

2019-03-02 08:15发布

问题:

I have a form:

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

After submitting the form, in the URL the input becomes example.com/?genres%5B%5D=jazz&genres%5B%5D=blues&genres%5B%5D=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

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.

回答1:

you can do it like this:

<!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>

in results.php you should:

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

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 ,)