1. 发送ajax请求的方式

  • 方案一:jq 的ajax(在 vue 中不推荐同时使用)
  • 方案二:js 原始官方 fetch方法
  • 方案三:axios 第三方

2. 方案一

  • 后端视图函数
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response


class Index(ViewSet):
    def index(self, request):
        res = Response({'name': 'xwx', 'age': 123})
        res['Access-Control-Allow-Origin'] = '*'
        return res

需要注意的是,需要添加 Access-Control-Allow-Origin 在请求头

  • 后端路由
from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.Index.as_view({'get': 'index'})),
]
  • 前端发送 Ajax
<div id="app">
    <p><button @click="func">点我向后端发请求,获取用户信息</button></p>
    <p>用户名:{{ name }}</p>
    <p>年龄是:{{ age }}</p>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            name: '',
            age: '',
        },
        methods: {
            func() {
                $.ajax({
                    'url': 'http://127.0.0.1:8000/index/',
                    'type': 'get',
                    success: data => {
                        console.log(data)
                        this.name = data.name
                        this.age = data.age
                    }
                })
            }
        },
    })
</script>

在这里插入图片描述

3. 方案二

  • 前端发送Ajax请求
<div id="app">
    <p>
        <button @click="func">点我向后端发请求,获取用户信息</button>
    </p>
    <p>用户名:{{ name }}</p>
    <p>年龄是:{{ age }}</p>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            name: '',
            age: '',
        },
        methods: {
            func() {
                fetch('http://127.0.0.1:8000/index/').then(res => res.json()).then(res => {
                    console.log(res)
                    this.name = res.name
                    this.age = res.age
                })
            },
        }
    })
</script>

4. 方案四

  • 前端发送Ajax请求
<div id="app">
    <p>
        <button @click="func">点我向后端发请求,获取用户信息</button>
    </p>
    <p>用户名:{{ name }}</p>
    <p>年龄是:{{ age }}</p>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            name: '',
            age: '',
        },
        methods: {
            func() {
                axios.get('http://127.0.0.1:8000/index/').then(res => {
                    console.log(res.data)
                    this.name = res.data.name
                    this.age = res.data.age
                })
            },
        }
    })
</script>
Logo

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

更多推荐