开发者

GET query through javascript with page reload, url rewriting problem

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:

  1. 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.
  2. is it a good idea to perform a GET query this way?

Thanks


  1. Don't use escape. Use encodeURIComponent.

    var q = encodeURIComponent($(this).val());

  2. Perfectly fine... although I wouldn't use URL rewriting on the parameters to a search.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜