为什么在IE中window.location会追加而不是替换URL?

10
我在IE中得到了错误的URL,但在Firefox和Chrome中没有问题。
基本上,我有一个名为text-search的文本字段。我正在使用jQuery和htaccess中的rewriterule来内部重定向页面。我在localhost上,所有文件都在一个名为test的文件夹中。
在Firefox和Chrome中,如果您在text-search框中输入“hello”并按回车,“hi”并按回车以及“goodbye”并按回车,您将得到正确的URL: localhost/test/testing/hello
以及 localhost/test/testing/hi
以及 localhost/test/testing/goodbye 而在IE中,则会出现以下情况: localhost/test/testing/hello
以及 localhost/test/testing/testing/hi
以及 localhost/test/testing/testing/testing/goodbye 问题在于'testing'被添加了。如何防止在IE中发生这种情况。我在网上找不到解决此问题的答案。
以下是html和jquery代码:
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>


        <base href="http://localhost/test/" />
        <script src="jQuery.js"></script>
        <script>
            $(document).ready(function(){
                $("#text-search").keyup(function(e){
                    if (e.keyCode == 13){
                        window.location.replace("testing/"+$('#text-search').val());
                    }
                })
            })
        </script>
    </head>

    <body>
        <input type='text' id='text-search'>
    </body>
</html>

.htaccess

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^testing/(.+)$ /test/testing.php?string=$1 [L]

Can you please help me on this. Many thanks

3个回答

13
如果你这样设置:window.location.href = '/yourpage',它会附加URL。为了避免这种情况,请使用//替代/,这样它会变成:window.location.href = '//yourpage'。请注意保留HTML标记。

12

window.location并不是一个字符串,如果你以这种方式使用它,那么一定要非常小心 - 它实际上是一个Location对象。

也许这会对你有所帮助:

var href = window.location.href;
window.location = href.replace(/testing\/.*$/, "testing/"+$('#text-search').val());

您还可以执行以下操作:

var href = "" + window.location;

强制将字符串转换为值传递。


你好,非常感谢你的帮助。我刚刚不得不将正则表达式更改为/testing.*$/,因为最初我有localhost/test/testing.php,之后我得到了localhost/test/testing/...,很抱歉上面没有说明清楚。现在它已经正常工作了。再次感谢。 - Hani

1

考虑当前URL栏中的链接为www.theunusualcards.com/marketing

我们将考虑两种情况:

第一种:**window.location = 'dummy-string'**

第二种:**window.location = '/another-dummy-string'**

在第一种情况下,它将进一步附加到URL中,而在第二种情况下,它将替换URL中的路径名(即/marketing)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接