【问题标题】:How to call a Django view function Asynchronously (AJAX) using Vue如何使用 Vue 异步调用 Django 视图函数(AJAX)
【发布时间】:2023-03-25 22:37:01
【问题描述】:

我有一个带有按钮的表单,而不是提交按钮。我希望 Vue 在单击该按钮时异步调用 Django 视图并返回一条 JSON 消息,说明函数已成功调用。

【问题讨论】:

  • 好的。那么你的问题是什么?你试过谷歌搜索“vue ajax”吗?

标签: ajax django vue.js vuejs2 django-views


【解决方案1】:

Jquery 和 Vue 不能很好地协同工作。 Vue 在 Jquery 中工作,但 Jquery 在 Vue 中不工作。更好的选择是将 Axios 用于 Ajax。 在 Vue 方法中调用 axios。

axios.defaults.xsrfCookieName = 'csrftoken' //need this for method:post
axios.defaults.xsrfHeaderName = 'X-CSRFToken' //need this for method:post

var vue_app = new Vue({
  el: '#id_xyz',
  data: {
    vue_var1:'hello',
    vue_var2:[],

  },
  methods:{
    ajax_method_name1:function(){
      console.log('Vue ajax_method_name1 is called');

      axios({
            method: 'post',
            url: 'ajax/url1/',//your customer url that is set in backend to do Ajax work
            data: {
                  axios_var1: this.vue_var1, //data to send to server

                },
            responseType: 'json', //server will response with this datatype
          })

          .then ( function (response){ //success function
              console.log('axios ajax success. data returned ==' + response.data); //if returned data format is like {[ {'id':1,'id':2} ]} we may have to do response.data['output_dict'][0]['id']
              this.vue_var2 = response.data['output_var'];
          }.bind(this)) //bind(this) is required when accessing Vue variable inside Axios success function (.then)

          .catch ( function (error){ //error function
            console.log('Axios ajax error');
          });

    },
  },

  delimiters: ["[[","]]"],
});

【讨论】:

    【解决方案2】:

    ARTICLE 中所述,有 4 种使用 Vue 进行 Ajax 的不同方法。

    我不完全理解。以下是使用 Jquery 的方法。

    Javascript 代码:

    $("#id1").blur(function() { //when field with id="id1" loses focus, Ajax happens
      var email_entered = $(this).val();
        $.ajax({
              url: 'ajax/signup_email_verification/',
              type: "POST", //needs csrf token
              data: { email: email_entered,csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), },
              dataType: 'json',
    
              success: function (data) {
                  alert("Ajax successful");
              },
              error: function(error){
                alert("Ajax error");
              },
            });
    });
    

    Django 代码:

    def email_verification(request):
        email=request.POST.get('email'); print('AJAX EMAIL = ',email)
        data={ 'success':True }
        return JsonResponse (data)
    

    HERE 是使用纯 JS 或 Jquery 或 Fetch 或 Axios 进行 Ajax 的少数首选方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多