1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| 规范; djangorestfremework框架 地址://www.django-rest-framework.org/
接口: 后端返回的是json格式的数据 资源:操作数据库中学生的信息,资源叫作student 请求方式:GET(查询)/POST(创建)/PUT(更新全部)/PATCH(更新部分)/DELETE(删除,路由中要有id参数)
定义路由 获取路由:couter = SimpleRouter() 注册资源:couter.register('student', StudentView) 获取urls地址:couter.urls 解析urls地址:urlpatterns += counter.urls
定义处理路由的业务逻辑
class StudentView(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin): # 查询返回的数据 queryset = Student.objects.filter(is_delete=0) # 序列化返回的文章的数据 serializer_class = StudentSerializer
def perform_destroy(self, instance): instance.is_delete = 1 instance.save()
class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fileds = ['id', 'name']
AJAX:
{% csrf_token %} var csrf = $('input[name="csrfmiddlewaretoken"]') $.ajax({ url: '/api/article/art/', type: 'GET', dataType: 'json', success: function(data) { console.log(data) for(var i=0; i<data.length; i+=1) { s = '<p>标题:' + data[i].title; s += ' 描述:' + data[i].desc; s += ' 内容:' + data[i].content; s += '<a href="javascript:;" onclick="del_art(' + data[i].id + ')">删除</a></p>'; $('#content').append(s) } }, error: function(data) { alert('失败') } });
简化: $.get(url, function(msg)) {}
|