【描述】
1.Server端定义了两个字段:Article.title 和 Article.content
2.客户端用JavaScript Ajax异步加载请求服务器的JSON数据
效果是点击按钮从服务器的数据库取得第一篇文章的标题
【实现】
网页端:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest){
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else{
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//取到的内容:一个JSON对象。相当于一个python的列表,列表里面是嵌套的字典
//[{"model": "cmdb.article", "pk": 1, "fields": {"title": "\u7b2c\u4e00\u4e2a\u6807\u9898", "content": "\u7b2c\u4e00\u6761\u5185\u5bb9\uff01\uff01\uff01"}}]
var ret=JSON.parse(xmlhttp.responseText)
//这里用.来取得对象的内容,之前没有考虑到是列表一直出现undefined的错误!
document.getElementById("myDiv").innerHTML=(ret[0].fields.title);
}
}
//这里url在django里面定义了,会用views.py里面的sendjson方法来处理请求
xmlhttp.open("GET","/thejson/",true);
xmlhttp.send();
} </script>
</head>
<body> <div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div>
<button type="button" onclick="loadXMLDoc()">修改内容</button> </body>
</html>
Django服务端:
#Views.py from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core import serializers
import json
from . import models
# Create your views here.
def sendjson(request):
articles= models.Article.objects.all()
data= serializers.serialize("json", articles)
print(data)
#抄别人的写法。
return HttpResponse(data,content_type="application/json") def hello(request):
return render(request,'index.html',locals())
#urls.py from django.contrib import admin
from django.urls import path
from cmdb import views urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.hello),
path('thejson/',views.sendjson),
]
#Models.py from django.db import models # Create your models here.
class Article(models.Model):
title=models.CharField(max_length=32,default='')
content=models.TextField(null=True) #这里可以让admin后台的文章列表显示正确的文章标题
def __str__(self):
return self.title