一、作用
用于使浏览器自动生成弹窗
二、示例
1、新建Django项目,新建APP:app01, 项目根目录下新建文件夹static
2、静态文件配置,在settings.py中配置static:
3、路由配置, urls.py:
from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('add/city/', views.add_city), ]
4、编写view函数,views.py:
from django.shortcuts import render, HttpResponse def index(request): """首页""" return render(request, "index.html", locals()) def add_city(request): """添加城市""" if request.method == "POST": # 获取数据 存入数据库 # ........ city_info = {"id": 5, "city": "成都"} return render(request, "pop-response.html", locals()) # 新建完成后自动关闭窗口 return render(request, "add_city.html")
5、templates模板编写:
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> <p><input type="text"></p> <p> <select id="city"> <option value=1>北京</option> <option value=2>天津</option> <option value=3>上海</option> <option value=4>深圳</option> </select> <input type="button" value="+" onclick="popUp();"> </p> </form> <script> function func(cityId, cityTitle){ //构造一个option标签 var tag = document.createElement("option"); tag.value = cityId; tag.innerText = cityTitle; //找到select框 将option添加进去 var city = document.getElementById("city"); city.appendChild(tag); } function popUp() { //打开新弹窗 (弹窗地址,弹窗名, 弹窗格式设置) window.open("/add/city/", "x1", "status=1, height=500, width=500, toolbar=0, resizeable=0"); } </script> </body> </html>
add_city.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box { 200px; height: 200px; border: 1px solid dodgerblue; } </style> </head> <body> <h3>新建城市</h3> <div class="box"> <form method="post"> {% csrf_token %} <input type="text" name="city"> <input type="submit" value="提交"> </form> </div> </body> </html>
pop-response.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>正在关闭</title> </head> <body> <script src="/static/commons.js"></script> {#引入文件,里面的'{{ id }}'不会被识别,就只是把它当做普通的字符串打印出来#} <script> //function close(){ //window.close(); //} //close(); // 自执行函数 在写完函数后, 后面直接加括号便可以执行,括号内可以传递参数, 执行效果同上 (function(){ // 获取到是谁把这个页面打开的 opener.func({{ id }}, "{{ city }}"); //传递参数 {"id": 5, "city": "成都"} window.close(); })(); // 可以传参: //(function(arg){ //})("x1") // arg=x1 </script> </body> </html>
6、static文件夹下新建文件commons.js:
alert('{{id}}'); //在pop-response.html中引入它
7、启动项目,在浏览器输入:http://127.0.0.1:8088/index/进入首页,点击按钮弹出新窗口,新增城市,提交后窗口自动关闭