javascript重定向不工作

时间:2015-04-30 13:59:19

标签: javascript forms

我有一个表单,它接受用户输入并将窗口重定向到URL,并将其输入附加到末尾。

这是我的HTML

        <form id="wikiForm">
            <label id="sideBarLabel">VoIP Services
                <input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
            </label>
            <input type="submit" value="Search" onclick="searchWiki();" />
        </form>

它运行的JavaScript

function searchWiki() {
    alert("Form Works!");
    var siteQuery = $('#query-string').val();
    window.location.href = "http://wiki.voipinnovations.com/dosearchsite.action?queryString=" + siteQuery;
    alert("SECOND MESSAGE");
}

问题是它没有重定向。它只附加了&#39; siteQuery&#39;变量到当前URL的末尾。我知道它调用javascript,因为我看到两个警报。我不确定我在这里做错了什么。

4 个答案:

答案 0 :(得分:1)

问题是由于您实际上是在提交表单,并且首先在表单提交时重定向丢失。有两种简单的方法可以解决这个问题:

  1. 将输入的类型从submit更改为button,或者
  2. 通过从您的函数返回false并将函数调用更改为onclick="return searchWiki();"
  3. 来停止提交表单

    jsFiddle example (1)

    jsFiddle example (2)

答案 1 :(得分:1)

原因是您使用type="submit",它会将GET标头提交并发送到默认的action参数(当前页面)。

type="submit"更改为type="button"

<form id="wikiForm">
    <label id="sideBarLabel">VoIP Services
        <input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
    </label>
    <input type="button" value="Search" onclick="searchWiki();" />
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
    function searchWiki() {
        alert("Form Works!");
        var siteQuery = $('#query-string').val();
        alert(siteQuery);
        window.location.assign("http://wiki.voipinnovations.com/dosearchsite.action?queryString=" + siteQuery);
        alert("SECOND MESSAGE");
    }
</script>

我尝试使用type="submit"代码及其警报,但没有重定向,因为在window.location更改之前优先处理提交,这就是它只是追加{{1}的原因到当前的网址。 如果您更改上面代码中显示的类型,它就能完美运行。

答案 2 :(得分:0)

使用默认的actionmethod属性

HTML表单元素提供了开箱即用的机制。

<form id="wikiForm" action="http://wiki.voipinnovations.com/dosearchsite.action" method="GET">
    <label id="sideBarLabel">VoIP Services
        <input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
    </label>
    <input type="submit" value="Search" />
</form>

但是,如果您必须使用javascript,请进行此更改:

自:

window.location.href = "…";

到:

window.location.assign("…"); // or
window.location = "…"

这是因为location.href是只读属性,location.assign()是设置要加载的新位置的正确方法。您也可以直接为location对象分配一个字符串:

  

每当为位置对象,文档分配新值时   将使用URL加载,就像调用了location.assign()一样   使用修改后的网址。

来源:MDN

答案 3 :(得分:0)

更改输入类型=提交到type = button

http://plnkr.co/edit/w4U7Sbm3XSKN8j3zUFMe?p=preview

<form id="wikiForm">
    <label id="sideBarLabel">VoIP Services
    <input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
    </label>
    <input type="button" value="Search" onclick="searchWiki();" />
</form>