如何将表单提交到新窗口?

问题描述 投票:6回答:4

我想使用JavaScript动态插入表单,然后提交并在新窗口中打开目标。

这是我的代码:

            var form = document.createElement("form");
            form.setAttribute("method", "post");
            form.setAttribute("action", xxx);
            form.setAttribute("onsubmit", "window.open('about:blank','Popup_Window','scrollbars=yes,width=550,height=520');");
            form.setAttribute("target", "Popup_Window");

            document.body.appendChild(form);
            form.submit();

此代码有效-它会动态插入表单并成功提交表单。但是,该窗体在新选项卡中打开,而我希望它在新窗口中打开。知道发生了什么吗?对于如何解决这个问题,有任何的建议吗?我也对jQuery开放。

谢谢!

编辑:我不确定为什么人们将其标记为重复。是的,它与另一个问题在同一主题上,但答案无关-所声称的重复问题有一个新行,弄乱了代码,我不知道,但是我的代码仍然行不通...

javascript jquery
4个回答
4
投票

我将其标记为重复,因为我认为您的问题与如何将表单发送到弹出窗口有关。以下是不使用onsubmit事件的方法:

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", xxx);

function submitToPopup(f) {
    var w = window.open('', 'form-target', 'width=600, height=400, any-other-option, ...');
    f.target = 'form-target';
    f.submit();
};

document.body.appendChild(form);

submitToPopup(form);

因此,不要使用onsubmit事件从那里创建弹出窗口,而是要在发送表单之前先创建它,然后再将表单发送给它。


3
投票

You could do this instead [link]

  1. 打开新窗口
  2. 插入表格
  3. 使其提交
  4. 将导航到网址

    var form = document.createElement("form");
    
    form.setAttribute("method", "post");
    form.setAttribute("action", "http://www.yahoo.com");
    
    
    function popitup() {
        newwindow = window.open('', 'name', 'width=800,height=600');
        if (window.focus) {
            newwindow.focus()
        }
        newwindow.document.body.appendChild(form);
        newwindow.document.forms[0].submit();
        return false;
    }
    
    popitup();
    

1
投票

据我所知,大多数浏览器和广告拦截器都会阻止这种脚本打开新窗口,因为它是自动运行的。但是,如果这样实现,则用户必须单击链接:JSFiddle,因此更有可能在新窗口中打开。

使用jQuery:

$('.open-popup').click(function(e) {
    e.preventDefault();
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "");
    document.body.appendChild(form);
    form.submit();
    window.open(this.href, '_blank', 'width=300,height=200');
});

HTML:

<a href="about:blank" class="open-popup">Click Me</a>

[此外,某些浏览器的首选项会自动禁止在新窗口中打开。因此,您可能想探索替代方法,或者只是要求用户在新标签中打开链接。


0
投票

如果要始终使弹出窗口保持“焦点”状态,可以使用最初发现的技巧here。通过快速打开/关闭/打开它,我们确保它始终像新窗口一样工作并抓住焦点。

 <form name=f1 method=post action=test.html>

  <input type=text name=name value='123'>

  <input type='submit' value='Submit' 

  onclick="if(window.open('','reuse_win') != null) {
       window.open('','reuse_win').close();
    }; this.form.target='reuse_win'; return true;">

</form>

也可以使用链接。

<a href="http://stackoverflow.com" onclick="
if(window.open('','reuse_win') != null) {
   window.open('','reuse_win').close();
}" target="reuse_win">Always opens in the same window and FOCUS</a>
© www.soinside.com 2019 - 2024. All rights reserved.