使用jQuery提交表单并在新窗口中打开

3
我有一个页面,其中包含两个文本框和 jQuery。我有一个按钮,并附带以下脚本。
  <input name="text1" type="text" id="text1" />
   <input name="text2" type="text" id="text2" />

<A class="floatRight button buttonAction3" href="#" name="save" id="save">Send</A>

我想要一个Jquery脚本来加载send.php,并在点击上面的按钮时将两个文本框的数据作为POST发送,然后send.php会在一个指定宽度和高度的新窗口中打开。实际上,我不想使用$.post来处理数据,我想要打开一个新窗口。
window.open()

然后在该窗口中打开一个带有POST数据的PHP文件。
谢谢。
2个回答

2
快速回答您的问题就是使用表单并添加target="_blank"属性,但这样做无法控制宽度和高度。
然而,我认为您应该改变解决问题的方式。这种方法会让扩展变得非常麻烦。使用jQuery可以更轻松地处理表单,而不是在页面中随机使用输入元素。
<form id="search" method="post" action="send.php">
  <input type="hidden" name="id" value="25">
  <input type="text" name="email" placeholder="bill@stackoverflow.com">
  <input type="submit" value="Send">
</form>

现在我们可以做到以下事情:
  // Sweet, the form was submitted...
  $('#search').submit(function(e){

    // Let's get the form with jQuery...
    $form = $(this);

    // Now you can do things like...
    $.post( $form.attr('action'), $form.serializeArray(), function( result ) {
        // "result" will inclue whatever the script returns...
    });

    // If you really need to open up the new window the only way I can think of controlling the size is with a get request...
    window.open( $form.attr('action') + '?' + $form.serialize(), 'PopUp', 'width=100,height=100' );

    // Stop the browsers default behavoir from kicking in!
    e.preventDefault()


});

1
$(document).ready(function() {
    $("#save").click(function(e) {
        e.preventDefault();
        $.post("send.php", { text1 : $("#text1").val(), text2 : $("#text2").val() },
              function(html) {
                  // open new window here
              }
    });
});

假设您的元素没有包装在表单中,则上述内容应该足够。解释:

  • 将单击处理程序绑定到保存按钮。使用e.preventDefault()防止链接的默认“操作”。
  • 使用jQuery的$.post高级ajax方法发布文本输入的两个值。
  • send.php将接收一个$_POST数组,它看起来像array("text1" => "thetext", "text2" => "thetext")
  • $.post的成功回调函数会在服务器将其响应发送回客户端后触发。这是您想要打开新窗口的地方。

参考:


首先,需要点击链接两次。其次,如果我使用window.open("page.php",null,"height=500,width=800,status=yes,toolbar=no,menubar=no,location=no,resizable=yes"),那么新窗口的加载代码将是什么?但是,post变量应该放在哪里? - air

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