day09: 前后分離,ajax
前后分離
## 規(guī)范:
djangorestframework框架
地址https://www.django-rest-framework.org/
## 接口、資源、請求方式
接口: 后端返回的是json格式的數(shù)據(jù)
GET /api/student/ 查詢所有學生信息
POST /api/student/ 創(chuàng)建學生信息
PUT/PATCH /api/student/id/ 修改學生信息
DELETE /api/student/id/ 刪除學生信息
GET /api/student/id/ 查詢指定id的學生信息
資源: 操作數(shù)據(jù)庫中學生的信息,資源叫做student
請求方式: GET/POST/PUT/PATCH/DELETE
## 定義路由
獲取路由: couter = SimpleRouter()
注冊資源: couter.register(‘student’,StudentView)
獲取urls地址: couter.urls
解析urls地址: urlpatterns += couter.urls
## 定義處理路由的業(yè)務邏輯
class StudentView(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin):
queryset = Student.obejcts.all()
# 序列化
serializer_class = StuSerializer
class StuSerializer(serializers.ModelSerilizer):
class Meta:
model = Student
fileds = ['id', 'name', 'sex']
ajax
## 最普通最常見的ajax寫法
{% csrf_token %}
var csrf = $('input[name="csrfmiddlewaretoken"]').val()
$.ajax({
url:'', ### 請求的地址
type: '', ### http請求方式POST/PUT....
data:{'name': '小明','age': 12}, ### 傳遞參數(shù)
dataType:'json',
headers:{'X-CSRFToken': csrf},
success:function(msg){},
error:function(msg){}
})
## 簡化版
$.get(url, funcion(msg)){}
$.post(url, {'name': '小明'}, function(msg){})
# 排除錯誤: F12(開發(fā)者工具)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。