django簡單的前后端分離的數據傳輸實例 axios
前端使用的是vue,下面是axios的主要代碼
methods: { search: function () { var params = { content1: this.content1 } this.$axios.post('http://127.0.0.1:8000/search/', params) .then((response)=> { console.log(response); this.response1=response.data[’content1’] }) .catch(function (error) { console.log(error); }) }, find: function () { this.$axios.get('http://127.0.0.1:8000/find/', { params: { content2: this.content2 } }) .then((response)=> { console.log(response); this.response2=response.data[’content2’] }) .catch(function (error) { console.log(error); }) }, },
后端是django框架,代碼如下
@csrf_exemptdef search(request): post_content = json.loads(request.body, encoding=’utf-8’)[’content1’] print(type(post_content)) print('post_content是:') print(post_content) return JsonResponse({’content1’: ’post請求’ + post_content * 2, ’msg’: ’錯誤信息’}) @csrf_exemptdef find(request): find_content = request.GET.get(’content2’) print('find_content是:') print(type(find_content)) print(find_content) return JsonResponse({’content2’: ’get請求’ + find_content * 3})
這里主要是新手對axios和前后端分離開發的學習
補充知識:ajax在后端獲取不到請求參數,但是前端已經傳遞過去了
使用ajax如果使用的是post方式提交數據,如果不設置content-type為application/x-www-form-urlencoded的話,默認的模式text/plain;charset=utf-8。
在tomcat中對于post提交方式又做了特殊的處理如果提交方式為post而content-type又不等于application/x-www-form-urlencoded,在tomcat底層是不會去解析請求參數的,也不會放到requestparameter的map中,因此使用request.getParameter(name)也就獲取不到請求的參數了。
在瀏覽器中network中,一般post提交方式提交的數據也是會顯示在form date下,而不是request payload下。
以上這篇django簡單的前后端分離的數據傳輸實例 axios就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: