当前位置:Gxlcms > JavaScript > Popup弹出框添加数据实现方法

Popup弹出框添加数据实现方法

时间:2021-07-01 10:21:17 帮助过:12人阅读

本文实例为大家分享了Popup弹出框添加数据的具体代码,供大家参考,具体内容如下

逻辑

窗口P1中显示一组数据,并提供一个添加按钮
点击按钮,弹出新的浏览器窗口P2,在其中添加一条数据并提交后,窗口P2自动关闭
新添加数据动态添加到窗口P1中并被选中
所需知识:JS BOM 窗口对象;JS自执行函数

实现

下面在Django中简单实现下,因为比较简单,路由和视图就写在一起了。

1.路由和视图部分

  1. from django.conf.urls import url
  2. from django.shortcuts import render
  3. def p1(request):
  4. return render(request, 'p1.html')
  5. def p2(request):
  6. if request.method == 'GET':
  7. return render(request, 'p2.html')
  8. elif request.method == 'POST':
  9. city = request.POST.get('city')
  10. print('执行数据保存操作...')
  11. return render(request, 'popup.html',{'city':city})
  12. urlpatterns = [
  13. url(r'^p1.html/', p1),
  14. url(r'^p2.html/', p2),
  15. ]

2.访问视图p1,返回页面p1.html:

  1. <head>
  2. <meta charset="UTF-8">
  3. <title>p1页面</title>
  4. </head>
  5. <body>
  6. <h2>p1页面</h2>
  7. <select id="cityChoose">
  8. <option>上海</option>
  9. <option>北京</option>
  10. </select>
  11. <input type="button" value="添加" onclick="popupFunc();"/>
  12. <script>
  13. popupFunc = function () {
  14. window.open('/p2.html/', 'p2', "status=1, height:300, width:300, toolbar=0, resizeable=1")
  15. //open(url, name, 窗口参数),注意name不能重名
  16. };
  17. callback = function (city) {
  18. var opt = document.createElement('option');
  19. opt.innerText = city;
  20. opt.setAttribute('selected', 'selected');
  21. var selEle = document.getElementById('cityChoose');
  22. selEle.appendChild(opt);
  23. }
  24. </script>
  25. </body>

说明:

1、点击添加按钮,执行popupFunc:访问'/p2.html/',并在新窗口中打开页面p2.html
2、定义回调函数callback:它接收一个参数city,将其动态添加到下拉选项中并设置为选中状态。

3.弹出窗口中显示p2.html如下:

  1. <head>
  2. <meta charset="UTF-8">
  3. <title>p2页面</title>
  4. </head>
  5. <body>
  6. <h2>p2页面</h2>
  7. <form method="post">
  8. {% csrf_token %}
  9. <input type="text" name="city">
  10. <input type="submit" value="提交">
  11. </form>
  12. </body>

说明:这里没有指定form表单的action=url参数,用户输入数据后,默认提交到当前地址,即'/p2.html/',提交到视图p2

4.视图p2收到提交的数据后,传入模板并返回页面popup.html:

  1. <head>
  2. <meta charset="UTF-8">
  3. <title>正在返回</title>
  4. </head>
  5. <body>
  6. <script>
  7. (function (city) {
  8. window.opener.callback(city);
  9. window.close();
  10. })("{{ city }}")
  11. </script>
  12. </body>

说明:

  • 这里定义了JS自执行函数:它调用打开弹出窗口的窗口中的回调函数(即P1中的callback),并把用户输入数据作为参数传入;关闭自身。
  • 如果p2视图返回错误信息,也可以在popup.html中作显示(略)。
  • 自执行函数可以参考 JavaScript 自执行函数和 jQuery扩展方法

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行