Change Response URL without Redirect
Is it possible to change the response URL without performing a redirect?
The slightly longer story...
Due to a limitation with HTML forms the following does not work because the query string from the action URL is not submitted to the server:
<?php // handler.php ?>
...
<form action="handler.php?lost=value" method="get">
<input type="text" name="filter-keyword" value="" />
<input type="submit" name="do-submit" value="Submit" />
</form>
...
So I decided to switch to using the post method and create a separate filter handler script which simply constructs the correct query string for the "handler.php" file.
<?php // handler.php ?>
...
<form action="filter-handler.php" method="post">
<input type="hidden" name="preserve-qs" value="lost=value" />
<input type="text" name="filter-keyword" value="" />
<input type="submit" name="do-submit" value="Submit" />
</form>
...
// filter-handler.php
<?php
$new_url = 'handler.php?filter-keyword=' . $_POST['filter-keyword'];
if (isset($_POST['preserve-qs']) && $_POST['preserve-qs'] != '')
$new_url .= '&' . $_POST['preserve-qs'];
header("Location: $new_url");
?>
Is it possible to achieve this with开发者_运维百科out performing a redirect?
// filter-handler.php
<?php
$qs_args = array(
'filter-keyword' => $_POST['filter-keyword'];
);
if (isset($_POST['preserve-qs']) && $_POST['preserve-qs'] != '')
parse_str($_POST['preserve-qs'], $qs_args);
// Fake query string.
$_GET = $qs_args;
// handler script is blissfully unaware of the above hack.
include('handler.php');
// ???? HOW TO UPDATE QUERY STRING IN BROWSER ADDRESS BAR ????
// Following no good because it redirects...
//header("Location: $new_url");
?>
Yes and no.
No, because to actually really change the URL from the server side you have to make a redirect.
Yes, because there are other solutions to your problem.
Solution no. 1:
Change your code from the first example into:
<?php // handler.php ?>
...
<form action="handler.php" method="get">
<input type="hidden" name="lost" value="value" />
<input type="text" name="filter-keyword" value="" />
<input type="submit" name="do-submit" value="Submit" />
</form>
...
and this should result in proper URL (with lost=value
).
Solution no. 2 (ugly one):
Overwrite $_GET
array at the beginning of the script to cheat the application into believing the GET parameters were passed.
Solution no. 3 (about changing URL without redirect):
This solution is probably not for you, but it actually imitates changing URL. It is not on the server side, but it actually changes the URL for the user. This is called pushState
(demo here) and this is HTML5 / JavaScript feature.
If you can use JavaScript and make AJAX requests, this solution may be perfect for you (you can eg. call whatever URL you like and dynamically pass data you need, even altering the values of the form fields you would submit).
精彩评论