程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

2022暑期實踐(Django教程學習記錄)(第五周1)P57Ajax1

編輯:Python

P57Ajax
浏覽器通過url(GET方法)和表單形式(POST方法)向服務器發送請求時,頁面會刷新,數據會消失

Ajax向後台發送請求,發送數據不會刷新頁面
依賴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("請求發到後端了")

綁定事件的方式:
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(){
 //頁面框架加載完成後自動執行 bindBtn1Event(); }) function bindBtn1Event() {
 $("#btn1").click(function () {
 $.ajax({
 url: '/task_ajax/', type: 'post', data: {
 n1: 123, n2: 'abc', }, {
#將後端傳過來JSON的轉成字符串反序列化成JSON對象,使得前端可以直接調用#} 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)
# 可以利用django自帶模塊轉成json格式
from django.http import JsonResponse
return JsonResponse(data_dict)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved