繁体   English   中英

使用Javascript更改表单操作时IE中的错误,当method = get和URL包含哈希时

[英]Bug in IE when using Javascript to change a form action, when method=get and URL contains a hash

我在提交表单时使用Javascript来更改表单的URL。 如果该URL包含哈希字符串(#),则Internet Explorer会忽略它,并在此之前提交到html的一部分。 Firefox和Chrome都很好。

示范:

<script type="text/javascript">
function changeURL() {
    var myform = document.getElementById('myform');

    myform.setAttribute("action", "page2.html#hello"); 

    return false;
}
</script>

<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
    <input type="submit">
</form>

如果我将方法更改为“ 帖子 ”,那就没关系。 如果我使用“ 获取 ”,IE登陆page2.html但没有URL中的#hello

无论我是使用jquery还是仅使用javascript,都会发生这种情况,尝试以下各项:

myform.action = "page2.html#hello";

myform.attr("action", "page2.html#hello");

myform.get(0).setAttribute("action", "page2.html#hello"); 

任何建议(假设我必须将方法保持为'get',并且我必须在URL中使用哈希,并且我必须使用Javascript动态更改此操作)?

在IE8中我自己进行的测试表明它确实坚持哈​​希( #hello )位于URL中的查询字符串( ?foo=bar )之后。 遗憾的是,您的表单并不适合您,并且在提交表单时无法强制执行此操作。

尝试在表单中编码哈希:

<script type="text/javascript">
function changeURL() {
    var hidden = document.createElement('input');
    hidden.setAttribute("type", "hidden"); 
    hidden.setAttribute("name", "hash"); 
    hidden.setAttribute("value", "hello"); 
    var myform = document.getElementById('myform');
    myform.setAttribute("action", "page2.html"); 
    myform.appendChild(hidden); 
    // return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
    <input type="submit">
</form>

在page2.html的顶部,将其解压缩出来:

<script type="text/javascript">
var qs = window.location.search.substring(1);
var qsarr = qs.split("&");
for (var i=0; i<qsarr.length; i++) {
    var tarr = qsarr[i].split("=");
    if (tarr[0]==="hash") {
        window.location.hash = tarr[1];
    }
}
</script>

我相信IE只是与哈希表现不同,我不认为它是用于这个庄园。

以下没有javascript会产生相同的结果...显示在FF而不是IE中

<form action="#test" method="get">
    <input type="text" value="test" />
    <input type="submit" />
</form>

至少你知道这不是一个JavaScript问题。 我骗了问号lol oops。

最后,我们决定只更新window.location.href以转到新位置而不是提交表单。 这似乎是一个奇怪的答案,但实际上我们处理表单的方式意味着这不是一个问题。 即我们禁用所有表单字段(因此通常不会将任何查询字符串附加到URL),然后根据表单字段包含的内容生成几个不同的SEO友好样式URL之一,然后更新表单操作并提交表单。 所以现在我们做了所有这些,但不打扰提交表单,只需更改页面位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM