Ajax Asynchronous Partial Refresh
AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。 传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
Implement JSON strings with Javascrip objects to convert Json.parse () and Json.stringify ()
1. Serialization (converting Javascrip to JSON) using Json.stringify ()
console.log(JSON.stringify({'name':"baolin"}));
2. Deserialization (convert JSON to Javascrip) using Json.parse ()
console.log(JSON.parse('{"name":"baolin"}'));
CSRF Cross-site request forgery
Setting up CSRF authentication and transferring data to the back end
1. Define Csrf_token
{% Csrf_token%}
2. Forged key value pairs to the back end of the Csrfmiddlewaretoken key value pair
<!DOCTYPE html><HTML lang="en"><Head> <Meta CharSet="UTF-8"> <Title>Title</Title> <Script src="Https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></Script></Head><Body><P> <input type="Text" class="NUM1">+<input type="Text" class="Num2">=<input type="Text" class="ret">{%Csrf_token%}<input ID="Cal" type="button"Value="Sum"></P><Script>$("#cal"). Click (function () {var num1=$(". Num1"). Val (); //GetinputInput Val value var num2=$(". num2"). Val ();$.ajax ({URL:"/cal/", {# Send Ajax URL #} type:"POST", {# Request method is post or get #}data:{{# Date Indicates the value sent back end, if no data needed to send can be omitted #} "NUM1": Num1, {# submit data to the back end #} "Num2": Num2, csrfmiddlewaretoken:$ (' [name= ' Csrfmiddlewaretoken '] '). Val ()//When using post to submit data, you need Scrf_token verification (fixed format)}, Success:function (data) {//callback function, if the Ajax execution succeeds in returning the function, the date is/Send_ajax/The value returned is $ (". Ret"). val (data)//Writes the returned data to the class for RET to enter the Air})});</Script>
3.urls.py
fromimport urlfromimport adminfromimport= [ url(r'^admin/', admin.site.urls), url(r'^cal/', views.cal),]
4.views.py
def cal(request): if=="POST": # 获取前端 ajax 传入得值 = request.POST.get("num1") = request.POST.get("num2") # 将值转换为 int 类型 =int+int(num2) # 返回结果 return HttpResponse(ret) return render(request,"cal.html")
Using Ajax to realize the landing function of the page
1.urls.py Routing Configuration
fromimport urlfromimport adminfromimport= [ url(r'^admin/', admin.site.urls), url(r'^login/', views.login), # 页面登陆窗口 url(r'^index/', views.index), # 页面首页窗口 url(r'^logout/', views.log_out), # 退出用户 url(r'^reg/', views.reg), # 添加用户 url(r'^set_pwd/', views.set_pwd), # 修改当前用户密码]
2.views.py View Functions
fromDjango.shortcutsImportRender, redirect, HttpResponse fromDjango.contribImportAuth fromDjango.contrib.auth.modelsImportUser fromDjango.contrib.auth.decoratorsImportLogin_requiredImportJsondefLogin (Request):ifRequest.method== "POST": username=Request. Post.get ("User") password=Request. Post.get ("PWD")# Verify that the user password obtained through Ajax is correctUsers=Auth.authenticate (username=Username, password=Password# defines a dictionary for serializing data to the front endLoginresponse={"User":None,"ErrorMsg":None}ifUsers# If validation successfully defines session valueAuth.login (Request, users)# Assign a dictionary user to a valueloginresponse["User"]=UsernameElse:# Validation Failure in ErrorMsg assignmentloginresponse["ErrorMsg"]="User name or password error" # Return the dictionary to the front end returnHttpResponse (Json.dumps (loginresponse))returnRender (Request,"Login.html")# Implement validation using Django's own adorner login_required# validation fails jump to/login/path, otherwise return index.html page@login_required(Login_url='/login/')defIndex (Request):returnRender (Request,"Index.html")
3.login.html Front-End Template display
<!DOCTYPE html><HTML lang="en"><Head> <Meta CharSet="UTF-8"> <Title>Title</Title> <Script src="Https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></Script></Head><Body>{#用户登录 #}<Form action="">{%Csrf_token%}<P>Name<input type="Text" class="User"></P> <P>Password<input type="Password" class="PWD"></P> <input type="button"Value="Submit" class="LOGINBNT"><Spanclass="ErrorInfo"></Span></Form><Script> //Ajax User Login $ (". Loginbnt"). Click (function () {$.ajax ({URL:"/login/",type:"POST", data:{user:$ (". User"). Val (), pwd:$ (". Pwd"). Val (), csrfmiddlewaretoken:$ (' [name= ' Csrfmiddlewaretoken '] '). Val ()}, Success:function (data) {//Data is the backend receives the JSON string VAR data=Json.parse (data);{# Serialize JSON string to JS type Dictionary #} if(data["User"]) {Location.href="/index/";{# If the login is successful, the page jumps on the Frontend #}}Else{Console.log (data["ErrorMsg"]);var error_msg=data["ErrorMsg"];{# If the login is unsuccessful, remove the error message that the backend played #}$(". ErrorInfo"). HTML (error_msg). CSS ("Color","Red");{# put the error message behind the button #}SetTimeout (function () {{# Let the message disappear after 3 seconds #}$(". ErrorInfo"). HTML ("");}, the) } } }) })</Script></Body></Html>################### #index. html Templates<!DOCTYPE html><HTML lang="en"><Head> <Meta CharSet="UTF-8"> <Title>Title</Title> <!--Latest version of the Bootstrap core CSS file - <Link rel="stylesheet"Href="Https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"Integrity="Sha384-bvyiisifek1dgmjrakycuhahrg32omucww7on3rydg4va+pmstsz/k68vbdejh4u"Crossorigin="Anonymous"> <!--Optional Bootstrap theme files (typically not introduced) - <Link rel="stylesheet"Href="Https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"Integrity="Sha384-rhyon1irsvxv4nd0jutlngaslcjuc7uwjduw9svrlvryoopp2bwygmgjqixwl/sp"Crossorigin="Anonymous"> <!--The latest Bootstrap core JavaScript files - <Script src="Https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"Integrity="Sha384-tc5iqib027qvyjsmfhjomalkfuwvxzxupncja7l2mcwnipg9mgcd8wgnicpd7txa"Crossorigin="Anonymous"></Script></Head><Body> <Navclass="NavBar navbar-inverse">{# #} <!--Collect the Nav links, forms, andOther content forToggling - <Divclass="Collapse Navbar-collapse" ID="Bs-example-navbar-collapse-1"> <Ulclass="Nav navbar-nav navbar-right"> <Li><a href="#">{{Request.user}}</A></Li> <Li><a href="/logout/">Cancellation</A></Li> <Li><a href="/reg/">Add user</A></Li> <Li><a href="/set_pwd/">Change Password</A></Li> </Ul> </Div><!-- /. navbar-Collapse - </Nav></Body></Html>
Ajax Asynchronous Partial Refresh