在弹出窗口中提交表单,然后关闭弹出窗口

时间:2011-12-23 12:54:10

标签: javascript html popup

当我开始使用它时,这似乎是微不足道的!我的目标是:

  • 当用户点击某个按钮时,请在新窗口中打开一个表单。
  • 提交表单后,关闭弹出窗口并返回原始页面。相反的顺序也很好 - 也就是说,如果弹出窗口关闭然后表单提交,我没问题。

以下是我这样做的方式:

<form action="/system/wpacert" method="post" enctype="multipart/form-data" onsubmit="return closeSelf()" name="certform">
                <div>Certificate 1: <input type="file" name="cert1"/></div>
                <div>Certificate 2: <input type="file" name="cert2"/></div>
                <div>Certificate 3: <input type="file" name="cert3"/></div>

                <div><input type="submit" value="Upload"/></div>
            </form>

,Javascript看起来像这样:

<script type="text/javascript">
function closeSelf(){
    self.close();
    return true;
}
</script>

这似乎在IE8和Chrome上运行良好;但Firefox拒绝提交表格;它只是关闭弹出窗口。我可能做错了什么?

编辑:

忘记发布代码打开弹出窗口。这是:

<div><input type="submit" value="Upload Certificates" onclick="popupUploadForm()"/>

和相应的javascript:

function popupUploadForm(){
        var newWindow = window.open('/cert.html', 'name', 'height=500,width=600');
    }

5 个答案:

答案 0 :(得分:10)

我已经在我的机器上执行了代码,它也适用于IE和FF。

function closeSelf(){
    // do something

    if(condition satisfied){
       alert("conditions satisfied, submiting the form.");
       document.forms['certform'].submit();
       window.close();
    }else{
       alert("conditions not satisfied, returning to form");    
    }
}


<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
       <div>Certificate 1: <input type="file" name="cert1"/></div>
       <div>Certificate 2: <input type="file" name="cert2"/></div>
       <div>Certificate 3: <input type="file" name="cert3"/></div>

       // change the submit button to normal button
       <div><input type="button" value="Upload"  onclick="closeSelf();"/></div>
</form>

答案 1 :(得分:5)

我知道这是一个老问题,但是当我遇到类似的问题时,我偶然发现了它,并且只想分享我如何结束你所要求的结果,以便未来人们可以选择最适合他们情况的方法。

首先,我在表单中使用onsubmit事件,并将this传递给函数,以便更轻松地处理此特定表单。

<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data"  name="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

在我们的函数中,我们将提交表单数据,然后我们将关闭窗口。这将允许它提交数据,一旦完成,它将关闭窗口并返回到原始窗口。

<script type="text/javascript">
  function closeSelf (f) {
     f.submit();
     window.close();
  }
</script>

希望这可以帮助别人。享受!


选项2:此选项将允许您通过AJAX提交,如果成功,它将关闭窗口。这可以防止窗口在提交数据之前关闭。致函http://jquery.malsup.com/form/以了解他们在jQuery表单插件上的工作

首先,从表单/提交按钮中删除onsubmit / onclick事件。在表单上放置一个ID,以便AJAX可以找到它。

<form action="/system/wpacert" method="post" enctype="multipart/form-data"  id="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

其次,你要将此脚本放在底部,不要忘记引用该插件。如果表单提交成功,它将关闭窗口。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

    <script>
       $(document).ready(function () {
          $('#certform').ajaxForm(function () {
          window.close();
          });
       });
    </script>

答案 2 :(得分:4)

以下是我最终如何做到这一点:

        <div id="divform">
            <form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
                <div>Certificate 1: <input type="file" name="cert1"/></div>
                <div>Certificate 2: <input type="file" name="cert2"/></div>

                <div><input type="button" value="Upload" onclick="closeSelf();"/></div>
            </form>
        </div>
        <div  id="closelink" style="display:none">
            <a href="javascript:window.close()">Click Here to Close this Page</a>
        </div>

function closeSelf(){
    document.forms['certform'].submit();
    hide(document.getElementById('divform'));
    unHide(document.getElementById('closelink'));

}

hide()unhide()分别将style.display设置为'none''block'

不完全是我想到的,但这暂时还有。适用于IE,Safari,FF和Chrome。

答案 3 :(得分:1)

最上面的解决方案不起作用,因为提交将页面重定向到表单的端点并等待响应重定向。 我看到这是一个古老的问题,但被问到最多,甚至我都知道答案。这仍然是我正在实施的解决方案。 我试图通过Nonce保护它的安全,但是如果您不在乎,那就不需要了。

方法1: 您需要弹出表格。

document.getElementById('edit_info_button').addEventListener('click',function(){
        window.open('{% url "updateuserinfo" %}','newwindow', 'width=400,height=600,scrollbars=no');
    });

然后打开表格。

正常提交表格。

然后使用STRICT内容安全策略将呈现形式的HTTPResponse返回到模板(HTML文件)。 包含以下脚本的变量。对于对服务器的每个请求,Nonce都包含一个Base64 128位或更大的随机生成的字符串。

<script nonce="{{nonce}}">window.close()</script>

方法2:

或者您可以重定向到另一个假定关闭的页面... 其中已经包含window.close()脚本。 这将关闭弹出窗口。

方法3:

否则,最简单的方法是如果愿意的话使用Ajax调用。使用then()并从服务器检查对 httpresponse 的条件。成功后关闭窗口。 / p>

答案 4 :(得分:0)

也尝试这样

import tkinter as tk
from random import randint
from random import shuffle
import pygame
pygame.init()

class Controller(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        if True:
            self.frames = {}
            for F in (PageMG,):
                page_name = F.__name__
                frame = F(parent=container, controller=self)
                self.frames[page_name] = frame

                # put all of the pages in the same location;
                # the one on the top of the stacking order
                # will be the one that is visible.
                frame.grid(row=0, column=0, sticky="nsew")

            self.show_frame("PageMG")
        self.geometry("800x480")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class PageMG(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        x = MemGame(self)
        x.pack()


class Tile(object):
    def __init__(self, canvas, x, y, image, cardback):
        self.cardback = cardback
        self.canvas = canvas
        self.y = y
        self.x = x
        self.image = image

    def drawFaceDown(self):
        self.canvas.create_rectangle(self.x, self.y, self.x + 100, self.y + 100, fill = "white")
        self.canvas.create_image(self.x + 50, self.y + 50, image=self.cardback)
        self.isFaceUp = False

    def drawFaceUp(self):
        self.canvas.create_rectangle(self.x, self.y, self.x + 100, self.y + 100, fill = "white")
        self.canvas.create_image(self.x + 50, self.y + 50, image=self.image)
        self.isFaceUp = True

    def isUnderMouse(self, event):
        if(event.x > self.x and event.x < self.x + 100):
            if(event.y > self.y and event.y < self.y + 100):
                return True


class MemGame(tk.Frame):
    def __init__(self, master):
        super(MemGame, self).__init__(master)

        photoRestart = tk.PhotoImage(file="restart.png")
        imgRestart = tk.Label(self, anchor="s", image=photoRestart)
        imgRestart.image = photoRestart
        buttonRestart = tk.Button(self, activebackground="white",
                                  image=photoRestart, highlightthickness=0, borderwidth=0,
                                  command=lambda: self.restart())
        buttonRestart.place(x=560, y=200)

        photoDog = tk.PhotoImage(file="Dyr/dog.png")
        photoElefant = tk.PhotoImage(file="Dyr/elefant.png")
        photoFlamingo = tk.PhotoImage(file="Dyr/flamingo.png")
        photoFlodhest = tk.PhotoImage(file="Dyr/flodhest.png")
        photoKamel = tk.PhotoImage(file="Dyr/kamel.png")
        photoKatt = tk.PhotoImage(file="Dyr/katt.png")
        photoKroko = tk.PhotoImage(file="Dyr/krokodille.png")
        photoNeshorn = tk.PhotoImage(file="Dyr/neshorn.png")
        photoSkilpadde = tk.PhotoImage(file="Dyr/skilpadde.png")
        photoStruts = tk.PhotoImage(file="Dyr/struts.png")
        photoZebra = tk.PhotoImage(file="Dyr/zebra.png")
        photoLove = tk.PhotoImage(file="Dyr/love.png")

        photoCardback = tk.PhotoImage(file="cardback.png")
        self.cardback = photoCardback

        self.riktig_sound = pygame.mixer.Sound("riktig.wav")
        self.click_sound = pygame.mixer.Sound("camerashutter.wav")

        self.configure(width=650, height=480, bg="white")
        self.canvas = tk.Canvas(self, bg="white", width=550, height=480, highlightthickness=0, borderwidth=0)
        self.canvas.place(x=0, y=-30)
        self.tiles = []
        self.images = [
            photoDog,
            photoElefant,
            photoFlamingo,
            photoFlodhest,
            photoKamel,
            photoKatt,
            photoKroko,
            photoNeshorn,
            photoSkilpadde,
            photoStruts,
            photoZebra,
            photoLove
        ]

        selected = []
        for i in range(10):
            randomInd = randint(0, len(self.images) - 1)
            animalImg = self.images[randomInd]
            selected.append(animalImg)
            selected.append(animalImg)
            del self.images[randomInd]
        shuffle(selected)
        self.flippedTiles = []
        NUM_COLS = 5
        NUM_ROWS = 4

        for x in range(0, NUM_COLS):
            for y in range(0, NUM_ROWS):
                self.tiles.append(Tile(self.canvas, x * 108 + 10, y * 108 + 40, selected.pop(), photoCardback))

        for i in range(len(self.tiles)):
            self.tiles[i].drawFaceDown()
        self.flippedThisTurn = 0
        self.canvas.bind("<Button-1>", self.mouseClicked)

    def mouseClicked(self, event):
        for tile in self.tiles:
            if tile.isUnderMouse(event) and (self.flippedThisTurn < 2):
                if (not(tile.isFaceUp)):
                    self.clickSound()
                    tile.drawFaceUp()
                    self.flippedTiles.append(tile)
                    self.flippedThisTurn += 1

                if (self.flippedThisTurn == 2):
                    if (self.flippedTiles[-1].image == self.flippedTiles[-2].image): #check last two elements
                        self.riktig()
                    self.after(1000, self.checkTiles)

    def checkTiles(self):
        self.flippedThisTurn = 0

        if not(self.flippedTiles[-1].image == self.flippedTiles[-2].image):
            self.flippedTiles[-1].drawFaceDown()
            self.flippedTiles[-2].drawFaceDown()
            del self.flippedTiles[-2:]

    def restart(self):
        for i in range(len(self.tiles)):
            self.tiles[i].drawFaceDown()

    def riktig(self):
        pygame.mixer.Sound.play(self.riktig_sound)
        pygame.mixer.music.stop()

    def clickSound(self):
        pygame.mixer.Sound.play(self.click_sound)
        pygame.mixer.music.stop()


if __name__ == '__main__':
    c = Controller()
    c.mainloop()