python之路_popup功能实现实例

   如django中admin中添加数据时有这样的一个功能,如下:

  为实现如上的功能,我们使用的并不是ajax,而是popup,具体实现实例如下:

视图函数

from django.shortcuts import render

def index(request):
    return render(request,'index.html')

def pop(request):
    if request.method == "GET":
        return render(request, 'pop.html')
    else:
        user = request.POST.get('user')
        return render(request,'pop_response.html',{'user':user})

1、访问视图函数index,渲染index页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 id="i1">无所谓</h1>
    <a href="#" onclick="popUp()">点我点我</a>

    <script>
        //回调函数,函数名随便,获取弹出页面返回给的内容text
        function xxxpopupCallback(text) {
            document.getElementById('i1').innerHTML = text;
        }
//事件函数,执行指定路径对应的视图(打开新页面) function popUp() { //第一个'/pop/'指的是路径,第二个'/pop/'为别名,可以随便起 window.open( '/pop/', '/pop/' ,"status=1, height:500, width:600, toolbar=0, resizeable=0"); } </script> </body> </html>

  如上,此页面必须有两个函数,一个事件函数,用于执行弹出新页面的视图;一个为接收最终传回来的回调函数。

2、执行pop视图后,渲染出弹出的那个页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        <input type="text" name="user">
        <input type="submit" value="保存">
    </form>
</body>
</html>

3、新页面提交完数据,提交回原pop视图,视图处理完数据后,渲染一个新页面,页面的中与回调函数对应的函数负责返回数据及关闭弹出的新页面。此页面未展示显示效果。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>正在关闭</h1>
    <script>
        (function () {
            // 与原页面回调函数名保持一致,传递数据,并关闭弹出的页面
            opener.xxxpopupCallback("{{ user }}");
            window.close();
        })()
        
    </script>
</body>
</html>

  以上即是实现popup整个流程,可以根据实际需求进行完善使用。

posted @ 2018-03-07 21:04  骑猪走秀  阅读(1110)  评论(0编辑  收藏  举报