2014-01-23 61 views
1

我有一个文本框和我的ASP网页中的按钮。我正在使用JavaScript从文本框和按钮验证触发器。一旦验证无误,我正在尝试将用户重定向到其他页面。Location.href只是重新加载当前页

这里是我的代码:

HTML

<input style="background: url(images/find.png) no-repeat; padding-left:20px;"type="text" id="txtSearch" onkeyup="validChar(this);" onkeypress="checkKey(event)" name="txtSearch" /> 

<button class="locButton" id="btnsave" onclick="fncsave(event)">Search</button> 

JS

<script type="text/javascript"> 
function validChar(e) { 
    e.value = e.value.replace(/[^a-zA-Z0-9]/g, ''); 
    e.style.border = "2px inset #EBE9ED"; 
} 

function fncsave(e) { 
    //alert('test'); 
    var t = window.document.getElementById('txtSearch'); 
    if (t.value.length > 0) { 
     alert(t.value); 
     redirectPage(t.value); 
     //document.cookie = 'postbackcookie='; 
     //document.location.href = "www.mydomain.com/search.aspx?search_results.aspx?searchtext=" + t.value + "&folderid=0&searchfor=all&orderby=title&orderdirection=ascending"; 
     //return false; 
    } else { 
     e.preventDefault(); 
     t.style.border = "2px inset #CC0000"; 
     alert("Search Query is Blank..."); 
    } 
} 

function checkKey(e) { 
    var t = window.document.getElementById('txtSearch'); 
    var code = (e.keyCode ? e.keyCode : e.which); 
    if (code == 13) { //Enter keycode 
     if (t.value.length > 0) { 
      alert('enter press and ' + t.value); 
      document.cookie = 'postbackcookie='; 
      document.location.href = "www.mydomain.com/search.aspx?searchtext=" + t.value + "&folderid=0&searchfor=all&orderby=title&orderdirection=ascending"; 
      return false; 
     } else { 
      e.preventDefault(); 
      t.style.border = "2px inset #CC0000"; 
      alert('enter press and 0'); 
     } 
    } 
} 

function redirectPage(val) { 
    document.cookie = 'postbackcookie='; 
    document.location.href = "www.mydomain.com/search.aspx?search_results.aspx?searchtext=" + val + "&folderid=0&searchfor=all&orderby=title&orderdirection=ascending"; 
    return false; 
} 
</script> 

当按下时,页面刷新,而是要去按钮会发生什么search_results页面,它只是重新加载自己。我必须使用表单吗?

默认情况下,aspx页面在页面中有一个<form id="form1" runat="server"></form>,但我试图避免使用在服务器上运行它。

回答

1

document.location.href与相对路径只是要改变url的最后部分(即搜索)。

要改变整个路径,您应该在开头添加一个/。

所以:

window.location.href = '/searchtext=sadsd'; 

会让domain.com/some/url 导航到domain.com/newurl?searchtext=sadsd

只需更换最后一部分,你应该补充.. /到开始 所以:

window.location.href = '../searchtext=sadsd'; 

会让domain.com/some/url 导航到domain.com/newurl?searchtext=sadsd

此外,你应该使用了window.location而不是document.location,如下所示:What's the difference between window.location and document.location in JavaScript?

+0

我离开了代码的一部分。整个代码是:'www.mydomain.com/search.aspx?blah&blah&blah'。 'window.open(http://www.google.com);'没有任何问题... – Si8

+0

如果我使用这段代码:'window.location.href =“http://www.google.com”; '我可以在标签上看到进度条,同时显示'google.com',但不是去那里,而是刷新当前页面。 – Si8

+0

我不明白你写的与你写的问题有关。 这里是一个jsfiddle:http://jsfiddle.net/bqzh8/ 第一个搜索与您的代码,第二个搜索框是适当导航的版本 – Etai

相关问题