Django中Ajax的使用
一、前端程式碼
1、js實現:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> function ajax1() { var request; if(window.XMLHttpRequest) //首先建立XHR物件 { request = new XMLHttpRequest(); //IE7+,Firefox,Chrome,Qpera,Safari } else { request =new ActiveObject("Microsoft.XMLHTTP"); //相容IE5,IE6 } //1、"GET"方法 request.open("GET","url_1/",true) //初始化一個請求 request.send(); //將請求傳送到伺服器 //2、"POST"方法 //request.open("POST","url_2/",true) //request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //設定http的頭資訊,告訴web伺服器要傳送一個表單 //request.send("name=小明&age=11"); request.onreadystatechange = function() { if(request.readyState===4 && request.status===200) { var text = request.responseText; document.getElementById("div1").innerHTML= text; } } } </script> </head> <body> <input type="button" value="點一下" onclick="ajax1()"> </br> <div id="div1"></div> </body> </html>
上面的程式碼除了註釋另外再做一些解釋:
a、open(method,url,async) 初始化一個請求
-mothod:傳送請求方法(GET, POST)
-url:請求地址(相對地址、絕對地址)
-async:請求同步(false)/非同步(true預設)(ajax一般使用非同步請求)
open方法中URL也可以傳遞引數,和其他url傳遞引數的使用方法一致,如果不瞭解可以參考這篇部落格:
b、send(string) 將請求傳送到伺服器
在使用get方法時,引數都填寫在url中,因此string可以不填寫或null
如果是post方法,則一定要填寫引數
c、onreadystatechange事件對伺服器響應進行監聽
當request.readyState===4 && request.status===200時,說明後端資料返回正常,然後就可以通過XMLHttpRequest.responseText來獲取後端傳來的資料。其他獲取資料的方法或屬性還有:
·responseText:獲得字串形式的響應資料
·responseXML:獲得XML形式的響應資料(現在比較少,一般使用JSON的格式)
·status和statusText:以數字和文字形式返回HTTP狀態碼
·getAllResponseHeader():獲取所有的響應報頭
·getResponseHeader(xxx):查詢響應中的某個欄位的值
2、jquery實現(jquery中實現好像更方便,等我學完再來更,網上也有許多資料可以自行查閱)
二、後端程式碼
1、url.py
urlpatterns = [
url(r'^url_1/$', views.myAjax1, name='myAjax1'),
url(r'^url_2/$', views.myAjax2, name='myAjax2'),
]
2、views.py
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
def myAjax1(request):
return HttpResponse("helloworld!")
@csrf_exempt
def myAjax2(request):
if request.method == 'GET':
return HttpResponse("lalala")
else:
name = request.POST.get('name', '')
age = request.POST.get('age', '')
return HttpResponse(name+age)
裝飾器@csrf_exempt的功能是取消當前函式防跨站請求偽造功能。因為我網上找了很多Ajax新增csrf驗證都是通過jQuery來實現的,我還沒學jQuery,用js來實現csrf驗證網上又找不到資料,因此在這裡就先不用csrf驗證。在jQuery程式碼中我會新增csrf驗證。