【问题标题】:Javascript form submital works in webkit, fails elsewhereJavascript 表单提交在 webkit 中工作,在其他地方失败
【发布时间】:2009-09-10 16:43:40
【问题描述】:

我编写了这段代码来尝试将 url 作为 post 值发送到同一页面。该代码在 chrome 和 safari 中运行良好......但在 FF3 和 IE 中失败(我不太关心的最后一个,但我需要它在 Firefox 中工作)。在 FF3 和 IE 中,它会打开一个空白的新标签。关于 webkit 和其他浏览器通过 javascript 处理表单提交的方式之间的差异,我应该知道什么?

我使用的代码是这样的:

function posturl (url) {
        var myForm = document.createElement("form");
        myForm.method="post" ;
        var myInput = document.createElement("input") ;
        myInput.setAttribute("name", "url") ;
        myInput.setAttribute("value", url);
        myForm.appendChild(myInput);
        document.body.appendChild(myForm) ;
        myForm.submit();
        document.body.removeChild(myForm) ;
    }

编辑:也许我应该补充一点,它的工作方式是我将脚本用作锚标记中的 href。因此,当您单击链接时,它会将参数通过帖子传递到同一页面,从而相应地更新内容。

【问题讨论】:

    标签: javascript firefox forms post


    【解决方案1】:

    它适用于我的 Firefox 2、Chrome 2。这是我的完整测试页面:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <script>
        function posturl (url) {
            var myForm = document.createElement("form");
            myForm.method="post";
    
            var myInput = document.createElement("input") ;
            myInput.setAttribute("name", "url") ;
            myInput.setAttribute("value", 'http://www.google.com');
    
            myForm.appendChild(myInput);
            document.body.appendChild(myForm);
            myForm.submit();
            document.body.removeChild(myForm);
        }
        </script>
    </head>
    <body>
    <input type="button" value="posturl()" onclick="posturl()" />
    </body>
    

    一定有其他东西(可能与打开空白标签有关??WTF?)破坏了您的代码。

    Here's为什么它在 IE 中不起作用。

    【讨论】:

    • 谢谢。我最终通过将javascript函数调用从href内部更改为用onclick替换它来解决我的问题。这似乎起到了作用。我想这个问题毕竟不在于脚本:)
    • @Jarsen:你会发现 IE 还是搞砸了。请参阅我发布的链接。
    【解决方案2】:

    这应该适用于浏览器。但实际上我只是认为你需要一个值为 0 的 window.setTimeout。发生的情况是你试图在 JavaScript 有时间“呼吸”之前访问一个元素

    试试:

    window.setTimeout( function() { 
            myForm.submit();
            document.body.removeChild(myForm);
    }, 0 );
    

    【讨论】:

    • 我假设您的意思是用该代码替换方法的最后两行?我试过了,但即使在 webkit 中它也停止工作。也许我应该补充一点,它的工作方式是我将脚本用作锚标记中的 href。因此,当您单击链接时,它会将参数通过帖子传递到同一页面,从而更新内容。
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    相关资源
    最近更新 更多