redirect user to current page with some querystring using javascript

后端 未结 10 1912
無奈伤痛
無奈伤痛 2021-01-01 12:09

When a person clicks on a link, I want to do this:

  1. grab the text from a textbox
  2. encode the text
  3. redirect to currentpage.aspx?search=textboxva
相关标签:
10条回答
  • 2021-01-01 12:33

    The problem with appending something to window.location.href is what if you have already done that? You'll just keep appending "?search=..." multiple times. More importantly, it's more complicated than it needs to be.

    You're already using jQuery. Why not just do this?

    <form id="search" method="get">
    <input type="text" name="search">
    </form>
    <a href="#" id="go">Search</a>
    

    with:

    $(function() {
      $("#go").click(function() {
        $("#search").submit();
        return false;
      });
    });
    

    and then you don't have to worry about the right URL, encoding, etc.

    0 讨论(0)
  • 2021-01-01 12:42

    How about:

    window.location = "/currentpage.aspx?search=" + escape( $("#someId").val());
    

    or

    window.location = window.location.pathname + "?search=" + escape( $("#someId").val());
    

    Etc...

    0 讨论(0)
  • 2021-01-01 12:48

    What part isn't working?

    Try encodeURI() rather than escape().

    0 讨论(0)
  • 2021-01-01 12:50

    window.location.href = window.location.href + "?search=" + escape( $("#someId").val()); ?

    0 讨论(0)
  • 2021-01-01 12:50
    $("a").click(function() {
    
     document.location.href += "?search=" + encodeURIComponent($("#myTextBox").val());
    
    
    });
    
    0 讨论(0)
  • 2021-01-01 12:51

    You are changing the wrong location property if you only want to change the search string. I think you want to do this:

    location.search = "?search=" + encodeURIComponent( $("#someId").val());
    
    0 讨论(0)
提交回复
热议问题