时间:2021-07-01 10:21:17 帮助过:12人阅读
本文实例为大家分享了Popup弹出框添加数据的具体代码,供大家参考,具体内容如下
逻辑
窗口P1中显示一组数据,并提供一个添加按钮
点击按钮,弹出新的浏览器窗口P2,在其中添加一条数据并提交后,窗口P2自动关闭
新添加数据动态添加到窗口P1中并被选中
所需知识:JS BOM 窗口对象;JS自执行函数
实现
下面在Django中简单实现下,因为比较简单,路由和视图就写在一起了。
1.路由和视图部分
- from django.conf.urls import url
- from django.shortcuts import render
- def p1(request):
- return render(request, 'p1.html')
- def p2(request):
- if request.method == 'GET':
- return render(request, 'p2.html')
- elif request.method == 'POST':
- city = request.POST.get('city')
- print('执行数据保存操作...')
- return render(request, 'popup.html',{'city':city})
- urlpatterns = [
- url(r'^p1.html/', p1),
- url(r'^p2.html/', p2),
- ]
2.访问视图p1,返回页面p1.html:
- <head>
- <meta charset="UTF-8">
- <title>p1页面</title>
- </head>
- <body>
- <h2>p1页面</h2>
- <select id="cityChoose">
- <option>上海</option>
- <option>北京</option>
- </select>
- <input type="button" value="添加" onclick="popupFunc();"/>
- <script>
- popupFunc = function () {
- window.open('/p2.html/', 'p2', "status=1, height:300, width:300, toolbar=0, resizeable=1")
- //open(url, name, 窗口参数),注意name不能重名
- };
- callback = function (city) {
- var opt = document.createElement('option');
- opt.innerText = city;
- opt.setAttribute('selected', 'selected');
- var selEle = document.getElementById('cityChoose');
- selEle.appendChild(opt);
- }
- </script>
- </body>
说明:
1、点击添加按钮,执行popupFunc:访问'/p2.html/',并在新窗口中打开页面p2.html
2、定义回调函数callback:它接收一个参数city,将其动态添加到下拉选项中并设置为选中状态。
3.弹出窗口中显示p2.html如下:
- <head>
- <meta charset="UTF-8">
- <title>p2页面</title>
- </head>
- <body>
- <h2>p2页面</h2>
- <form method="post">
- {% csrf_token %}
- <input type="text" name="city">
- <input type="submit" value="提交">
- </form>
- </body>
说明:这里没有指定form表单的action=url参数,用户输入数据后,默认提交到当前地址,即'/p2.html/',提交到视图p2
4.视图p2收到提交的数据后,传入模板并返回页面popup.html:
- <head>
- <meta charset="UTF-8">
- <title>正在返回</title>
- </head>
- <body>
- <script>
- (function (city) {
- window.opener.callback(city);
- window.close();
- })("{{ city }}")
- </script>
- </body>
说明:
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。