1. Ajax交互数据填充
使用Ajax交互时,从后端传过来的数据类型:
都需要js中不同的操作进行填充
2. 示例代码
- 后端代码
这一部分的代码简单粗暴,首先DynamicPageView 使用GET方法返回页面,对应的其他类都使用GET方法返回对应类别的数据:
- ShowAjaxStringView:返回字符串类型
- ShowAjaxListView:返回列表类型
- ShowAjaxDictView:返回字典类型
from django.shortcuts import render
from django.views.generic import View
from .form import FormTestForm, SaveDataForm, SaveFileInDjangoForm
from .models import SaveDataModel, SaveFileInDjangoModel, MyModel
from django.core.paginator import Paginator
import matplotlib.pyplot as plt
from io import StringIO
from django.http import JsonResponse
class DynamicPageView(View):
def get(self, request):
return render(request, "dynamic_load.html")
class ShowAjaxStringView(View):
def get(self, request):
return JsonResponse("这是一个字符串", safe=False)
class ShowAjaxListView(View):
def get(self, request):
return JsonResponse([1, 2, 3, 4, 5], safe=False)
class ShowAjaxDictView(View):
def get(self, request):
return JsonResponse({
"name": "小明",
"age": 12,
"兴趣": "搬砖",
}, safe=False)
- 前端代码
前端代码里,包含三个【p】标签,分别要填充:
- id=“show_string”:字符串
- id=“show_list”:列表
- id=“show_dict”:字典
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AJAX局部刷新实例</title>
</head>
<body>
<input type="button" value="显示Ajax返回值" id="ajax_button">
<hr>
字符串:<p id="show_string"></p>
<hr>
列表:<p id="show_list"></p>
<hr>
字典:<p id="show_dict"></p>
<hr>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#ajax_button").on("click", function () {
$.ajax({
url: "/show_ajax_num/",
type: "GET", data: {},
success: function (data) {
$("#show_string").html(data);
}
})
$.ajax({
url: "/show_ajax_list/",
type: "GET", data: {},
success: function (data) {
for (let i = data.length - 1; i >= 0; i--) {
$('#show_list').append(' ' + data[i])
}
}
})
$.ajax({
url: "/show_ajax_dict/",
type: "GET", data: {},
success: function (data) {
$.each(data, function (dict_key, dict_value) {
$("#show_dict").append(dict_key)
$("#show_dict").append(dict_value)
})
}
})
})
</script>
</body>
</html>
- 配置路由:
from django.urls import path
from .views import DynamicPageView, ShowAjaxStringView, ShowAjaxListView, ShowAjaxDictView
urlpatterns = [
path('django_ajax/', DynamicPageView.as_view()),
path("show_ajax_num/", ShowAjaxStringView.as_view()),
path("show_ajax_list/", ShowAjaxListView.as_view()),
path("show_ajax_dict/", ShowAjaxDictView.as_view()),
]
3. 效果图
访问:http://127.0.0.1:8000/django_ajax/ ,可以看到:
点击【显示Ajax返回值】,可以看到:
|