如django中admin中添加数据时有这样的一个功能,以下:html
为实现如上的功能,咱们使用的并非ajax,而是popup,具体实现实例以下:ajax
视图函数django
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})
一、访问视图函数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>
如上,此页面必须有两个函数,一个事件函数,用于执行弹出新页面的视图;一个为接收最终传回来的回调函数。post
二、执行pop视图后,渲染出弹出的那个页面spa
<!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>
三、新页面提交完数据,提交回原pop视图,视图处理完数据后,渲染一个新页面,页面的中与回调函数对应的函数负责返回数据及关闭弹出的新页面。此页面未展现显示效果。3d
<!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整个流程,能够根据实际需求进行完善使用。code