学习笔记,仅供参考,有错必纠 参考自:Django打造大型企业官网–Huang Y; JsonResponse类 如果我们想向浏览器传递Json类型数据,可以使用JsonResponse类。该类会将对象dump成
学习笔记,仅供参考,有错必纠
参考自:Django打造大型企业官网–Huang Y;
JsonResponse类
如果我们想向浏览器传递Json类型数据,可以使用JsonResponse类。该类会将对象dump成json字符串,然后返回将json字符串封装成Response对象返回给浏览器,并且他的Content-Type为application/json
- 举个例子(传递字典)
主urls.py文件:
from django.contrib import adminfrom django.urls import path
from . import views
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = "index"),
path("redirect/", views.redir, name = "redir"),
path("front/", include("front.urls")),
path("add_book/", views.add_book, name = "add_book"),
path("show_response/", views.show_response, name = "show_response"),
path("show_json/", views.show_json, name = "show_json"),
]
主views.py文件:
def show_json(request):person = {
"username":"Huang",
"age":19,
"height":30
}
response = JsonResponse(person)
return response
向http://127.0.0.1:8000/show_json/发起请求
- 举个例子(传递列表)
主views.py文件:
def show_json(request):person = [
{
"username":"Huang",
"age":19,
"height":30
},
{
"username":"Bai",
"age":20,
"height":32
},
]
response = JsonResponse(person, safe = False)
return response
向http://127.0.0.1:8000/show_json/发起请求: