djangoAPI返回json——前后端分离(查询图书)
Posted 嘴巴嘟嘟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了djangoAPI返回json——前后端分离(查询图书)相关的知识,希望对你有一定的参考价值。
- 创建django项目
- 连接数据库
setting.py 配置文件修改
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1', # 数据库主机
'PORT': 3306, # 数据库端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'xxxx', # 数据库用户密码
'NAME': 'name' # 数据库名字
}
}
_init _.py 调用数据库
import pymysql
pymysql.install_as_MySQLdb()
- 建立应用
python manage.py startapp users
- 配置路由
from django.urls import path,include
urlpatterns = [
path('', include(('users.urls', 'users'), namespace='users')),
]
- 操作数据库
models.py
class Book(models.Model):
book_name = models.CharField(max_length=128)
add_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.book_name
- 业务逻辑
views.py
from django.shortcuts import render
# Create your views here.
import json
from django.http import HttpResponse
# Create your views here.
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.http import JsonResponse
import json
from .models import Book
# http://127.0.0.1:8000/add_book/?book_name=三国演义
@require_http_methods(["GET"])
def add_book(request):
response = {}
try:
book = Book(book_name=request.GET.get('book_name'))
book.save()
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
# http://127.0.0.1:8000/show_books
@require_http_methods(["GET"])
def show_books(request):
response = {}
try:
books = Book.objects.filter()
response['list'] = json.loads(serializers.serialize("json", books))
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
子路由的配置
from django.urls import path
from users import views
urlpatterns = [
path('add_book/', views.add_book, name="add_book"),
path('show_books/', views.show_books, name="show_books"),
]
- 前端业务逻辑
<!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.0">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th>序号</th>
<th>书名</th>
</tr>
</thead>
<tbody id="dataList">
</tbody>
</table>
<h2>添加图书</h2>
<label for="name">
书名:<input type="text" name="name" id="book_name">
</label>
<input type="button" value="保存图书" id="getall">
</body>
<script src="./js/jquery.min.js"></script>
<script>
var htmlStr = '';
$.ajax({
type: "get",
url: "http://127.0.0.1:8000/show_books/",
contentType: "application/json",
success: function (response) {
if (response.status = 200) {
var list = response.list;
list.forEach(element => {
htmlStr += '<tr><td>' +
element.fields.book_name
+ '</td><td>' + element.fields.add_time
+ '</td></tr>';
});
document.getElementById("dataList").innerHTML = htmlStr
} else {
alert("错误啦")
}
}
});
// 保存图书功能
document.getElementById("getall").onclick = () => {
var book_name = document.getElementById("book_name").value
$.ajax({
type: "GET",
url:'http://127.0.0.1:8000/add_book/?book_name='+String(book_name),
success: function (response) {
console.log(response)
if(response.msg=="success"){
alert('保存成功')
}
return location.replace(document.referrer);
}
});
}
</script>
</html>
当然直接使用请求是存在跨域问题的
我们可以在django项目中解决跨域问题
# 此时跨域解决的办法是 修改django的setting.py文件如下图(不是唯一解决方法)
# 解决之前需要安装 pip install django-cors-headers:
setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
-
前端界面
-
完结
以上是关于djangoAPI返回json——前后端分离(查询图书)的主要内容,如果未能解决你的问题,请参考以下文章