I want to create a url in the form of domain.com/?product=value1&product2=value2.....
Sometimes the textboxes may not have values in it. How can I edit the code below to ignore those forms elements?
my form
<form action="customsearch.php">
<input type="text" class="textfield" value="" id="product" name="product">
<input type="text" clas开发者_如何学编程s="textfield" value="" id="product2" name="product2">
.
.
.
<input type="submit" value="Send">
</form>
Re your updated question: You can redirect from server side to a new, nicer URL, but I'm not sure this makes sense. It would probably be better to do this in JavaScript.
You could use http_build_query()
.
$url = http_build_query($_POST);
as @David Fells points out, this will however not remove empty values.
You could do a
$post_elements = array_filter($_POST, "strlen");
$url = http_build_query($post_elements );
which is just as well, but don't do this with large amounts of data.
Also, if I were you, I would do this using $_GET
instead of $_POST
.
note that if you're planning to use this for a GET request, the overall size of the data shouldn't exceed 2-4 kilobytes due to server side and browser side restrictions on the maximum length of URLs.
<?php
foreach ($_POST as $k => $v)
{
if ('' == $v) {
$url .= "&".urlencode($k).'='.urlencode($v);
}
}
?>
Don't use "if ($v)" because if someone enters a 0 into a field, it won't add it. You just want to test '', empty string.
Adding a new answer since the question was entirely changed...
There's no reason for this. Browsers construct query strings based on standards. If youw ant to ignore empty fields on the backend, do so. If for some stylistic reason you just can't stand them there, then use jQuery and manually construct the URL and redirect to it on click - but this is not the expected or normal way to submit a form.
精彩评论