P57Ajax
浏覽器通過url(GET方法)and form(POST方法)向服務器發送請求時,頁面會刷新,數據會消失
Ajax向後台發送請求,Sending data does not refresh the page
依賴jQuery
ajax代碼
$.ajax({
url:'xxx',
type:'post',
data:{
n1:123,
n2:'abc',
},
success:function(res){
console.log(res);
}
})
免除ajax的post方式的csrf_token認證
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def task_ajax(request):
print(request.GET)
return HttpResponse("The request is sent to the backend")
綁定事件的方式:
1.基於dom方式
<input type="button" class="btn btn-primary" value="點擊" onclick="clickMe();"/>
2.基於jQuery方式
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<h1>任務列表</h1>
<h3>示例1</h3>
{# <input type="button" class="btn btn-primary" value="點擊" onclick="clickMe();"/>#}
<input type="button" class="btn btn-primary" id="btn1" value="點擊" />
</div>
{% endblock %}
{% block js %}
<script type="text/javascript"> {
#基於dom方法綁定事件#} {
#function clickMe(){
#} {
# console.log("點擊了按鈕");#} {
# $.ajax({
#} {
# url: '/task_ajax',#} {
#type: 'get',#} {
# type: 'post',#} {
# data: {
#} {
# n1: 123,#} {
# n2: 'abc',#} {
# },#} {
# success: function (res){
#} {
# console.log(res);#} {
# }#} {
# })#} {
# } #} $(function(){
//Executed automatically after the page frame is loaded bindBtn1Event(); }) function bindBtn1Event() {
$("#btn1").click(function () {
$.ajax({
url: '/task_ajax/', type: 'post', data: {
n1: 123, n2: 'abc', }, {
#Pass the backend overJSONConverted into a string deserialized into JSON對象,So that the front end can be called directly#} dataType: "JSON", success: function (res) {
console.log(res); console.log(res.data) } }) }) } </script>
{% endblock %}
後端代碼:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def task_ajax(request):
print(request.GET)
data_dict = {
"status": True,
"data": [11, 22, 33, 45],
}
# import json
# json_string = json.dumps(data_dict)
# return HttpResponse(json)
# 可以利用djangoThe built-in module is converted intojson格式
from django.http import JsonResponse
return JsonResponse(data_dict)