Window open()使用方法

open() 方法用于打开一个新的浏览器窗口或查找一个已命名的窗口

window.open(URL,name,specs,replace)

URL 可选。打开指定的页面的URL。如果没有指定URL,打开一个新的空白窗口
name 可选。指定target属性或窗口的名称
specs 可选。一个逗号分隔的项目列表 设置新的窗口得长,高,和位置等
replace Optional.Specifies规定了装载到窗口的 URL 是在窗口的浏览历史中创建一个新条目,还是替换浏览历史中的当前条目。支持下面的值:
true - URL 替换浏览历史中的当前条目。
false - URL 在浏览历史中创建新的条目。

1.在页面上,点击打开新窗口时,则打开指定得窗口

<h1>window open 应用</h1>
<button onclick="f()">打开新窗口</button>
<script>
    function f() {
        window.open("https://www.cnblogs.com/","","width=600,height=300,top=100")
    }
</script>

2.点击后,页面跳转到添加页面,提交后,窗口关闭

在打开得新窗口中添加完数据后,窗口关闭,应该在另建一个新的页面,在该页面上写上使窗口关闭得代码,让页面跳转到该页面
def add(request):
    if request.method=='POST':
        title=request.POST.get("title")
        price = request.POST.get("price")
        models.Food.objects.create(price=price,title=title)
        return render(request,"pop.html")
    return render(request,"add.html")
pop.html
<script>
     window.close()
</script>

3.点击后,页面跳转到添加页面,提交后,窗口关闭,添加的数据显示到页面上

1.点击添加按钮时,为了将数据再返还给此页面,应该识别是哪个按钮进行的提交操作,因此对每个按钮添加个类作识别
2.在给window open传递地址时,将这个类值作为参数传递过去,这个后端在处理完数据后,也能知道返还给谁
3.后端处理完,要跳转到关闭窗口的页面,将传递的数据传到这个页面,这个页面再将数据给显示页面。
用window.opener接收
4.再显示页面找到对应的标签,将值赋给该标签
add.html
<form action="" method="post">
    {% csrf_token %}
    <p>
        <label for="title">食物名称</label>
         <input type="text" id="title" name="title">
    </p>
   <p>
         <label for="price">食物价格</label>
        <input type="text" id="price" name="price">
   </p>
    <p><input type="submit" value="提交"></p>
</form>
index.html
<h1>window open 应用</h1>
<button onclick="f(this)" class="show1">添加数据1</button>
<p id="show1"></p>
<hr>
<button onclick="f(this)" class="show2">添加数据2</button>
<p id="show2"></p>
<script>
    function f(self) {
        为路径添加参数,self.className获得该标签类的值
        url="/add/?pop="+self.className;
        window.open(url,"","width=600,height=300,top=100")
    };
    function bar(arg,pop){
        var ele=document.getElementById(pop);
        ele.innerText=arg;
    }
</script>
pop.html 关闭窗口页面

<script>
    window.opener.bar("{{ food.title }}","{{ pop }}");
    window.close()
</script>
def index(request):
    return render(request,"index.html")
def add(request):
    if request.method=='POST':
        title=request.POST.get("title")
        price = request.POST.get("price")
        ##只要路径上有参数,POST请求中也可以使用GET
        pop=request.GET.get("pop")
        food=models.Food.objects.create(price=price,title=title)
        return render(request,"pop.html",{"food":food,"pop":pop})
    return render(request,"add.html")
原文地址:https://www.cnblogs.com/zgf-666/p/9175323.html