render 的执行流程
流程 :
render 只能识别 字符串,对于其他的css,html,js,jquery样式是不能识别的,它会将文件中的内容解析称为字符串拿到前端页面,浏览器进行渲染.
例如 :
# 视图函数 def index(request): if request.is_ajax(): return HttpResponse("成功了呢!") name = 'fily' return render(request,"index.html",{"name":name})
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="/static/js/jquery-3.3.1.min.js"></script> </head> <body> <div class="c1">全局首页:{{ name }}</div> {% load cal %} {{ n1|mul:13 }} <button class="c2">Ajax</button> <div id="i1" user="{{ name }}"></div> <script> $(".c1").click(function () { $(this).css("color","red") }); $(".c2").click(function () { $.ajax({ url:"", type:"get", data:{ name:"1" }, success:function (res) { alert(res) } }) }) </script> </body> </html>
实现效果 : 点击全局首页---变红 点击ajax按钮---将1传递到视图函数中,页面显示.
需求 :
想点击ajax之后,name=fily的fily传到后端做一个校验(校验不用了,传过去就行.)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="/static/js/jquery-3.3.1.min.js"></script> </head> <body> <div class="c1">全局首页:{{ name }}</div> {% load cal %} {{ n1|mul:13 }} <button class="c2">Ajax</button> <div id="i1" user="{{ name }}"></div> <script> $(".c1").click(function () { $(this).css("color","red") }); $(".c2").click(function () { $.ajax({ url:"", type:"get", data:{ name:"{{ name }}" }, success:function (res) { alert(res) } }) }) </script> </body> </html>
注意 : 在html中,我们在jQuery中,name:'{{ name }}' 一定要加 ' ' .否则后面的name就是一个变量.(因为' ' 里面的是字符串,render只能识别字符串)
render 的执行流程 : 对于render来说,它会找到对应的html文件,但是它对html,css,js,jquery 是不识别的,唯一识别的就是 字符串 ,它会将 index.htnl文件解析成字符串,在这些字符串中只有 {{ }} 和 {% %} 这些模板语法会被响应的替换. 拿整个模板的字符串交给浏览器进行渲染(浏览器是可以识别html,css等).