注意:由于axios发送post、put、delete请求时默认携带的参数是json对象格式,django后端不能正常接收参数,所以axios发送请求之前需要先把json数据转化为form-data格式的数据。

(1) 下载qs, axios

cnpm install qs
cnpm install axios --save

(2)main.js中导入,并进行全局注册,代码第三步中包含了

(2)post、put、delete请求的参数需要用this.$qs.stringify()方法转换掉就可以了

1. django后端接口代码

from django.views.generic.base import View
from django.http import JsonResponse, QueryDict


class JsonData(View):
    def get(self, request):
        id = request.GET.get("id")
        res = self.choice(id)
        return JsonResponse(res, safe=False)

    def post(self, request):
        id = request.POST.get("id")
        res = self.choice(id)
        return JsonResponse(res, safe=False)

    def delete(self, request):
        id = QueryDict(request.body).get("id")
        res = self.choice(id)
        return JsonResponse(res, safe=False)

    def put(self, request):
        id = QueryDict(request.body).get("id")
        res = self.choice(id)
        return JsonResponse(res, safe=False)

    @staticmethod
    def choice(id):
        if id == "1":
            res = {"name": "mayanan", "age": 29}
        elif id == "2":
            res = [11, 22, 33, 44]
        else:
            res = ["npm", "run", "build"]
        return res

2.  app.vue代码

<template>
  <div id="app">
    <button v-on:click="getJson">点击获取数据</button>
<!--    后端返回的是字典 -->
    <ul>
      <li v-for="(value, key) in info" v-bind:key="key">
        {{ key }} : {{ value }}
      </li>
    </ul>
    <li>哈哈哈</li>
    <li>嘿嘿嘿</li>
<!--    后端返回的是列表 -->
<!--    <ul>-->
<!--      <li v-for="(value, index) in info" v-bind:key="value">-->
<!--        {{ index }} : {{ value }}-->
<!--      </li>-->
<!--  </ul>-->
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      info: ''
    }
  },
  methods: {
    getJson: function () {
      // axios请求里面不能直接用Vue实例this,所以在发请求之前我们可以定义一个变量等于this
      let that = this
      this.$axios
        // get方法传递参数的两种方法
        // .get('http://127.0.0.1:8000/app01/json_data/?id=1')
        .get('http://127.0.0.1:8000/app01/json_data/', {params: {id: 2}})

        // post传递参数的方法,$qs.stringify方法可以将json对象转化为form-data格式的数据
        // 如果不转化,django后台接收的数据为None,转化了才能正常接收post请求携带的参数
        // .post('http://127.0.0.1:8000/app01/json_data/', this.$qs.stringify({id: 1}))

        // delete请求传递参数的方法:需要加上data参数
        // .delete('http://127.0.0.1:8000/app01/json_data/', {data: this.$qs.stringify({id: 1})})

        // PUT请求传递参数的方法,需要将json数据转化为form数据
        // .put('http://127.0.0.1:8000/app01/json_data/', this.$qs.stringify({id: 1}))
        .then(function (response) {
          that.info = response.data
        })
        .catch(function (err) {
          alert(err)
        })
    }
  },
  computed: {
  },
  watch: {
  }
}
</script>

<style>
</style>

3. main.js代码

import Vue from 'vue'
import App from './App'
// import router from './router'
import axios from 'axios'
import qs from 'qs'

// 全局注册
Vue.config.productionTip = false
Vue.prototype.$axios = axios
Vue.prototype.$qs = qs

/* eslint-disable no-new */
new Vue({
  el: '#app',
  // router,
  components: { App },
  template: '<App/>'
})

4. urls.py文件中的代码

from django.urls import path
from app01 import views
from django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    path("json_data/", csrf_exempt(views.JsonData.as_view()), name="json_data")
]

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐