JQuery時代,咱們使用ajax向後臺提交數據請求,Vue時代,Axios提供了前端對後臺數據請求的各類方式。javascript
Axios是基於Promise的Http客戶端,能夠在瀏覽器和node.js中使用。css
Axios很是適合先後端數據交互,另外一種請求後端數據的方式是vue-resource,vue-resource已經再也不更新了,且只支持瀏覽器端使用,而Axios同時支持瀏覽器和Node端使用。前端
Vue開發者推薦使用更好的第三方工具,這就是Axiosvue
Axios的安裝支持多種方式java
npm install axios
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
接下來,咱們使用Django,搭建一個後臺程序,並使用Vue Cli搭建一個前端程序,使用Axios進行先後端數據交互。node
vue init webpack luffy_fontend
`django-admin startproject luffy_backend`
cd luffy_backend python manage.py startapp courses
from django.db import models # Create your models here. class Courses(models.Model): course_name = models.CharField(max_length=32) course_price = models.IntegerField() course_teacher = models.CharField(max_length=16) start_date = models.DateField(auto_now=True, null=False) end_date = models.DateField(auto_now=True, null=False) def __str__(self): return self.course_name class Students(models.Model): student_name = models.CharField(max_length=16) student_id = models.IntegerField() student_phone = models.IntegerField() student_address = models.CharField(max_length=128)
// courses_courses insert into courses_courses(course_name, course_price, course_teacher, start_date, end_date) values('Python全棧中級開發', 12800, 'Pizza', '2018-10-01', '2018-10-02'); insert into courses_courses(course_name, course_price, course_teacher, start_date, end_date) values('Python全棧高級開發', 19800, 'Alex', '2018-10-03', '2018-10-04'); insert into courses_courses(course_name, course_price, course_teacher, start_date, end_date) values('Linux高級運維', 12800, 'Oldboy', '2018-10-05', '2018-10-06'); insert into courses_courses(course_name, course_price, course_teacher, start_date, end_date) values('高級網絡工程師', 12800, 'Egon', '2018-10-07', '2018-10-08'); insert into courses_courses(course_name, course_price, course_teacher, start_date, end_date) values('Go全棧高級開發', 12800, 'Yuan', '2018-10-09', '2018-10-10'); insert into courses_courses(course_name, course_price, course_teacher, start_date, end_date) values('Vue高級開發', 12800, 'Xiaoma', '2018-10-11', '2018-10-12'); // courses_students insert into courses_students(id, student_name, student_id, student_phone, student_address) values(1, 'Alex', 100001, 1378061875, '北京市大興區智障一中'); insert into courses_students(id, student_name, student_id, student_phone, student_address) values(2, 'Pizza', 100002, 1378161875, '北京市朝陽區第一中學'); insert into courses_students(id, student_name, student_id, student_phone, student_address) values(2, 'Egon', 100003, 1378261875, '北京市房山智障三中'); insert into courses_students(id, student_name, student_id, student_phone, student_address) values(4, 'Oldboy', 100004, 1378361875, '北京市大興區智障三中'); insert into courses_students(id, student_name, student_id, student_phone, student_address) values(5, 'Yuanhao', 100005, 1378460275, '北京市豐臺區智障四中'); insert into courses_students(id, student_name, student_id, student_phone, student_address) values(6, 'Jinxin', 100006, 1378560875, '北京市海淀區智障五中');
from django.shortcuts import render, HttpResponse from rest_framework.views import APIView import json from luffy_backend import settings from .models import Courses from .models import Students # Create your views here. class CoursesView(APIView): def get(self, request): print("Courses Get Methods Exec!") courses = list() for item in Courses.objects.all(): course = { "course_name": item.course_name, "course_price": item.course_price, 'course_teacher': item.course_teacher, 'start_date': str(item.start_date), 'end_date': str(item.end_date) } courses.append(course) print(courses) return HttpResponse(json.dumps(courses, ensure_ascii=False)) class StudentsView(APIView): def get(self, request): print("Student Get Methods Exec!") students = list() for item in Students.objects.all(): student = { 'student_name': item.student_name, 'student_id': item.student_id, 'student_phone': item.student_phone, 'student_address': item.student_address } students.append(student) return HttpResponse(json.dumps(students, ensure_ascii=False)) def post(self, request): print("Student Post Methods Exec!") print(request.body.decode('utf-8')) response = json.dumps(request.POST) return HttpResponse(response)
注意,修改配置文件後,須要重啓前端服務器。python
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' import axios from "axios" Vue.prototype.$axios = axios; Vue.config.productionTip = false; new Vue({ el: '#app', router, template: '<App></App>', components: { App }, store: store });
<template> <div> <span>這是課程詳情頁面</span> <button @click="getCourses">點擊獲取所有課程</button> <div v-if="isShow"> <table border="1"> <thead> <tr> <th>課程名稱</th> <th>課程價格</th> <th>授課老師</th> <th>開課日期</th> <th>結課日期</th> </tr> </thead> <tbody> <tr v-for="(course, index) in courses" :key="index"> <td>{{ course.course_name }}</td> <td>{{ course.course_price }}</td> <td>{{ course.course_teacher }}</td> <td>{{ course.start_date }}</td> <td>{{ course.end_date }}</td> </tr> </tbody> </table> </div> </div> </template> <script> export default { name: "Courses", data() { return { isShow: false, courses: [] } }, methods: { getCourses: function () { let ts = this; this.$axios.get('/api/course/1/') .then(function (response) { ts.isShow = true; ts.courses = response.data; }) .catch(function (error) { console.log(error); }); } } } </script> <style scoped> </style>
<template> <div> <span>這是學員信息頁面</span> <button @click="getStudents">點擊獲取學生信息</button> <button @click="changeStudents">點擊修改學生信息</button> <div v-if="isShow"> <table border="1"> <thead> <tr> <th>學生ID</th> <th>學生姓名</th> <th>學生電話</th> <th>學生地址</th> </tr> </thead> <tbody> <tr v-for="(student, index) in students" :key="index"> <td>{{ student.student_id }}</td> <td><input v-model="student.student_name"/></td> <td><input v-model="student.student_phone"/></td> <td><input v-model="student.student_address"/></td> </tr> </tbody> </table> </div> </div> </template> <script> export default { name: "Students", data() { return { isShow: false, students: [] } }, methods: { getStudents: function () { let ts = this; this.$axios.get('/api/student/1/') .then(function (response) { console.log(response); ts.isShow = true; ts.students = response.data; }) .catch(function (error) { console.log(error); }) }, changeStudents: function () { let ts = this; this.$axios.post('/api/student/2/', { student_name: 1, student_id: 100001, student_phone: 1347658765, student_address: "北京市石景山區智障六中" }) .then(function (response) { }) .catch(function (error) { console.log(error); }) } } } </script> <style scoped> </style>
發送post請求時,須要解決跨域問題,咱們採用在Django中自定義一個處理跨域問題的中間件來解決這個問題。webpack
from django.utils.deprecation import MiddlewareMixin class MyCore(MiddlewareMixin): def process_response(self, request, response): response["Access-Control-Allow-Origin"] = '*' if request.method == 'OPTIONS': response["Access-Control-Allow-Headers"] = 'Content-Type' response["Access-Control-Allow-Methods"] = 'POST, DELETE, PUT' return response
以上,就是咱們經過Axios的get和post請求與後臺進行數據交互的全過程。ios