Location.href只是重新加载当前页面

时间:2014-01-23 20:43:51

标签: javascript jquery html asp.net

我的ASP网页上有一个文本框和一个按钮。我正在使用JavaScript来验证文本框和按钮的触发器。验证完成后,我正在尝试将用户重定向到其他页面。

这是我的代码:

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 个答案:

答案 0 :(得分:1)

带有相对路径的

document.location.href只会改变网址的最后一部分(即搜索)。

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

所以:

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?