一、视图创建
from django.http import JsonResponse
from django.shortcuts import render# Create your views here.
from django.views import Viewclass IndexView(View):def get(self,request):# 前后端分离 (前端JS代码渲染数据)return JsonResponse({'name':'Hello,mike'})
二、配置子路由
from django.urls import pathfrom book import viewsurlpatterns = [#子路由path('', views.IndexView.as_view()),]
三、配置主路由
from django.contrib import admin
from django.urls import path, includeurlpatterns = [path('', include('book.urls')), #子路由path('admin/', admin.site.urls),
]
四、解决跨域查看(Python 安装django-cors-headers解决跨域问题-CSDN博客)
五、HTML页面
my.html页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>前后端分离数据</title><script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script><script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">{{name}}</div>
<script>new Vue({el:'#app',data:{name:'',},mounted:function () {axios.get('http://127.0.0.1:8000').then(response=>{this.name=response.data.name}).catch(error=>{alert(error)})},})
</script>
</body>
</html>
六、运行前后端服务
http://127.0.0.1:8000
http://127.0.0.1:8080/my.html
效果: