使用window.location重定向不起作用

时间:2014-12-31 18:46:15

标签: javascript redirect window.location

我搜索了相关帖子,但所有尝试都没有奏效。

我的问题是,我尝试使用path + querystring在Javascript中进行简单的重定向。我的代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="WebApplication1.Page1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="submit" value="pesq" onclick="Redirect();"/>
    </div>
    </form>
    <script>
        function Redirect()
        {
          window.location.href = 'http://localhost:61267/Page1.aspx?q=name';            
        }
    </script>
</body>
</html>

window.location.href始终设置为'http://localhost:61267/Page1.aspx'

我尝试过使用window.location.search但仍然没有成功。

我做错了什么?

5 个答案:

答案 0 :(得分:3)

请改用document.location。

      document.location = 'http://localhost:61267/Page1.aspx?q=name';  

答案 1 :(得分:3)

问题代码:

<form id="form1" runat="server">
<div>
<input type="submit" value="pesq" onclick="Redirect();"/>
</div>
</form>

HTML元素,特别是表单,具有在用户操作发生时发生的默认事件。在您的上下文中,单击submit框时可能会调用input事件。您需要通过从事件处理程序返回false或调用preventDefault

来阻止发生默认事件
<form onsubmit="Redirect(); return false;" id="form1" runat="server">
  <div>
    <input type="submit" value="pesq" onclick="Redirect(); return false;"/>
  </div>
</form>

P.S。

onsubmit处理程序将允许您自己按Enter键,并且仍然具有与单击input框时相同的效果。

答案 2 :(得分:1)

不确定为什么需要表单和提交按钮才能进行重定向。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="WebApplication1.Page1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <div>
    <input type="button" value="pesq" onclick="Redirect();"/>
    </div>

        <script>
        function Redirect()
        {
          window.location.href = 'http://www.google.com';            
        }
    </script>
</body>
</html>

我还注意到一些编码问题,我可以通过添加:

来解决
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

答案 3 :(得分:0)

您需要执行以下任一操作:

1)对于服务器端的asp代码:

<asp:button text="Navigate" onclientclick="Redirect()" value="pesq" runat="server" />

See MSDN Example

2)如果是客户端代码:

<input type="button" value="pesq" onclick="Redirect();"/> 

答案 4 :(得分:0)

仅更改了输入类型,并且完美运行!感谢t.niese。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="WebApplication1.Page1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="pesq" onclick="Redirect();return false;"/>
    </div>
    </form>
    <script>
        function Redirect()
        {
            window.location.href = 'http://localhost:61267/Page1.aspx?q=name';                        
        }
    </script>
</body>
</html>