描述: 点击界面按钮获取后台图书,不刷新页面获取后台数据,实现Ajax获取数据
1、 配置URL
from django.contrib import admin from django.urls import path from app1 import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index), ## 配置登录首页 path('book/',views.select_all), ## 配置Ajax跳转页面 ]
2. 配置views
from django.shortcuts import render,HttpResponse import json # Create your views here. def index(request): ## 配置转发访问首页 return render(request, "index.html") def select_all(request): ## 模拟获取后台数据 data = [ {'title':"廊道", "price":"122", "publish":"清华大学出版社"}, {'title':"朱自清自传1", "price":"322", "publish":"北大大学出版社"}, {'title':"朱自清自传2", "price":"322", "publish":"北大大学出版社"}, {'title':"朱自清自传3", "price":"322", "publish":"北大大学出版社"}, ] return HttpResponse(json.dumps(data)) ## 将字典转化为字符串
3. 配置index.html
(1) 配置页面内容 index.html 前端内容
(2) 配置Ajax不刷新页面
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://lib.baomitu.com/jquery/3.5.1/jquery.js"></script> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <title>Document</title> </head> <body> <h1>首页</h1> <button type="button" class="btn btn-primary">点击我查看数据</button> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2" > <table class="table table-striped table-bordered"> <thead> <tr> <th>书籍名称</th> <th>价格</th> <th>出版社</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </div> <script>
## Ajax 核心配置内容 $(function () { $(".btn").on("click",function () { ## 鼠标点击.btn标签进行操作 $.ajax({ url: "/book", ## 跳转获取数据 dataType: "json", ## 定义数据类型 success:function (data) { ## 请求成功返回信息 total = ''
## $.each()是对数组,json和dom结构等的遍历 $.each(data,function (i,book) { ## book指的是一个个的数据字典 {title: "朱志清", price: 223, publish: "清华大学出版社"等等 i:指的是序号 var title = book.title var price = book.price var publish = book.publish strvar = ` <tr> <td>${title}</td> <td>${price}</td> <td>${publish}</td> </tr> ` total += strvar ##获取数据写入一个空间,循环拼接字符串 }) $("tbody").html(total) ##插入到tbody这个标签中 }, error:function (data) { console.log("数据请求失败") } }) }) }) </script> </body> </html>
4. 验证
【登录页面】
【点击查看数据】