2014-01-23 59 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

相關問題