2013-10-18 35 views
0

fI'm在开发一个WordPress页面的简单和小的搜索当前URL的一部分:

<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不是我所需要的。

谢谢。

+2

的可能重复[我怎样才能查询字符串值?(http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values) – maerics

回答

0

凡是搜索天真的将是脆弱的像这样的问题:如果什么网址是:

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

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

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

这工作,但' &'仍在重复。这是什么样的规则?这是否像preg-match? – user2375094

+0

嗯,好吧,我猜你可以添加一个'.replace(/&$ /,'')'来删除它。如果你想把它比作PHP,它基本上是'preg_replace'。 –

+0

现在工作就像一个魅力。谢谢。我会了解这些规则。我仍然是一个新手。 – user2375094

0

试试这个希望它应该工作

<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()'> 
0

的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> 

希望帮助。

相关问题