I use url r开发者_如何学Cewriting on one of my projects, and I would like to be able to perform queries through a search box with javascript by, on a "type enter" event, grabbing the value of this search box and passing it through a GET request to another search page. The end result would be a search address a la twitter (ie mysite.com/search/mykeyword). My code is the following:
$("#search-box").keyup(function(event) {
var code = (event.keyCode ? event.keyCode : event.which);
if (code == "13") { // ENTER
var q = $(this).val();
document.location.href = "/search/"+q;
}
});
2 questions:
- how can I sanitize the q string with JS to avoid having a non url encoded string with spaces or special characters? (of course it doesn't work if i type any of these values). I tried the function escape but it still doesn't work.
- is it a good idea to perform a GET query this way?
Thanks
Don't use escape. Use
encodeURIComponent
.var q = encodeURIComponent($(this).val());
Perfectly fine... although I wouldn't use URL rewriting on the parameters to a search.
精彩评论