How to change form url parameter on submit?

2019-02-24 11:29发布

问题:

I have this form for processing..

<form action="driver.php" method="GET">
<input type="text" placeholder="Search" id="search" name="n">
<button type="submit">Submit</button>
</form>


by default the url is http://sites.com/driver.php?n=typedname

so i did modifications in .htaccess and convert it to http://sites.com/driver/typedname for SEO friendly urls modrewrite issue - 404 error thanks to anubhava

everything is well, but the problem now comes when I type and click the submit button, it will go to http://sites.com/driver.php?n=typedname

so how can I make it to go this url http://sites.com/driver/typedname instead after clicking submit?

I think javascript can do this, so i tagged it, hope im not wrong.

thanks.

回答1:

jQuery

$('button[type=submit]').click(function(e){
    e.preventDefault();
    e.stopPropagation();

    window.location = "http://sites.com/driver/" + $('#search').val();

    return false;
});

or

$('form').submit(function(e) { // you really need to class/ID your form
    // all that code
});

Now this is quick and dirty to give you the idea. You'd of course want to sanitize your input (good idea to do that on the front-end as well as the back-end).



回答2:

You will have to handle form submit event yourself. Something like this:

document.querySelector('form').addEventListener('submit', function(e) {
    e.preventDefault();
    location.href = '/driver/' + this.elements.n.value;
}, false);