• vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现。
  • axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护。

参考:GitHub上搜索axios,查看API文档

1 login.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  7. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  8. </head>
  9. <body>
  10. <div id="app">
  11. <span>[[ message ]]</span>
  12. <button @click="login">登录Get</button>
  13. <button @click="login2">登录Post</button>
  14. <hr>
  15. [[ username ]]
  16. </div>
  17. </body>
  18. <script>
  19. var vm = new Vue({
  20. el: "#app",
  21. delimiters: ["[[", "]]"],
  22. data: {
  23. message: "hello",
  24. username: "11",
  25. },
  26. methods: {
  27. login: function() {
  28. var url = "http://127.0.0.1:8000/recv/?username=itcast&password=1234"
  29. axios.get(url).then((response)=>{
  30. console.log(response.data.info.username)
  31. this.username = response.data.info.username
  32. }).catch((err)=>{
  33. console.log(err);
  34. })
  35. },
  36. login2: function() {
  37. url = "http://127.0.0.1:8000/recv/"
  38. axios.post(url, {
  39. "username": "苏轼",
  40. "password": "123456",
  41. }).then((response)=>{
  42. console.log(response.data.info.username)
  43. this.username = response.data.info.username
  44. }).catch((err)=>{
  45. console.log(err);
  46. })
  47. }
  48. }
  49. })
  50. </script>
  51. </html>

1.因为Vue的模板变量和django的模板变量分隔符冲突,所以需要修改Vue的分隔符delimiters:[“[[“,”]]”] 2.箭头函数解决这个指向的问题

2 view.py

  1. from django.shortcuts import render
  2. from django.views import View
  3. from django.http import JsonResponse, HttpRequest
  4. import json
  5. # Create your views here.
  6. class LoginView(View):
  7. def get(self, request):
  8. return render(request, "login.html")
  9. def post(self, request):
  10. ...
  11. class RecvView(View):
  12. def get(self, request):
  13. data = request.GET
  14. username = data.get("username")
  15. password = data.get("password")
  16. return JsonResponse({"info": {"username": username}})
  17. def post(self, request: HttpRequest):
  18. data = json.loads(request.body.decode())
  19. username = data.get("username")
  20. password = data.get("password")
  21. return JsonResponse({"info": {"username": username}})