【问题标题】:Get part of the current URL using Javascript使用 Javascript 获取当前 URL 的一部分
【发布时间】:2013-10-27 10:23:14
【问题描述】:

我正在使用 javascript 传递的 url 中的 $_GET 变量在 Wordpress 页面中开发一个简单而小型的搜索:

<script>
function pesquisar()
{
    var pesquisar = document.getElementById('termo').value;
    var caminho = document.URL+'&pesquisa='+pesquisar;
    window.location = caminho;
}
</script>

<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>

所以,要搜索的网址是:MYURL/?page_id=51&pesquisa=test

当然,page_id 是可变的。如果我再次搜索,URL 将是:MYURL/?page_id=51&pesquisa=test&pesquisa=new,这是怎么回事。

如何使用 javascript 只获取 MYURL/?page_id=51 ? window.location.pathname 不是我需要的。

谢谢。

【问题讨论】:

标签: javascript


【解决方案1】:

javascript:

<script type="text/javascript">

function get_query_param(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

window.onload = function() {
    if (get_query_param("page_id") != null) {
        alert(window.location.pathname + "?page_id=" + get_query_param('page_id'));
    }
}
</script>

希望有帮助。

【讨论】:

    【解决方案2】:

    任何天真地搜索的东西都容易出现这样的问题:如果 URL 是:

    http://example.com/?pesquisa=test&page_id=51

    您需要搜索并删除相关的查询参数:

    var caminho = document.URL.replace(/([?&])pesquisa=[^&]+&?/,"$1")+"&pesquisa="+pesquisar;
    

    【讨论】:

    • 这行得通,但“&”仍在重复。这是什么规矩?这有点像预赛吗?
    • 啊是的...好吧,我想您可以添加一个额外的.replace(/&amp;$/,'') 来删除它。如果你想把它比作 PHP,它基本上是preg_replace。
    • 现在就像一个魅力。谢谢。我将了解这些规则。我还是个新手。
    【解决方案3】:

    试试这个。

    var a = document.URL;
        var result = a.substr(0, a.indexOf('&'));
    

    资源:

    【讨论】:

      【解决方案4】:

      试试这个希望它会工作

      <script>
      function pesquisar()
      {
          var pesquisar = document.getElementById('termo').value;
          var caminho = location.protocol + '//' + location.host + location.pathname+'&pesquisa='+pesquisar;
          window.location = caminho;
      }
      </script>
      
      <input type='text' id='termo'>
      <input type='button' value='pesquisar' onclick='pesquisar()'>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-05
        相关资源
        最近更新 更多