开发者

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 redire开发者_如何转开发ct 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/...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜