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

2022 Summer Practice (Django Tutorial Learning Record) (Fifth Week 1) P57Ajax1

編輯:Python

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)

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