赞
踩
- 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'})),
- ]
- <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>
- <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>
- <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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。