简体   繁体   中英

Rewriting form urls with javascript

Search forms go to ugly urls normally. If I want users to see nice urls I need to rewrite them on server side and http redirect them.

I'd like to avoid this round trip and rewrite this urls by some simple javascript code. (without javascript on you'll get the usual http redirect)

What's the most reliable way to do that?

If, for example, your ugly URI takes the form of

/search.php?query=[input]

and your nice URI takes the form of

/search/[input]

Keep the round-trip implementation (with PHP redirects and URL rewriting) in case the client does not have JavaScript. For those who do, intercept the submit event of the form in question (using the event object's preventDefault method), and in your event handler, do something like

location = '/search/' + encodeURIComponent(queryInputObject.value);
<form action="http://host/target" method="get">
    ...
    <input type="text" name="query" value="..." />
    <input type="submit" value="Search" />
</form>

Would give http://host/target?query=...

With plain JS, you could add a listener to the onSubmit event (untested):

<form action="http://host/target" method="get" onsubmit="window.location.href=this.action + '/' + encodeURIComponent(this.elements['query'].value); return false;">
    ...
    <input type="text" name="query" value="..." />
    <input type="submit" value="Search" />
</form>

Would give http://host/target/...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM