【问题标题】:Sending data from a Django template to views.py via Ajax通过 Ajax 将数据从 Django 模板发送到 views.py
【发布时间】:2020-06-22 22:34:53
【问题描述】:

我正在通过 ajax 将一些数据从 html 模板发送到 views.py。从发送到 views.py 的 id 我正在创建 sql 记录。但是我想知道是否有任何方法可以将数据从 views.py 发送到模板以通知数据已添加到 sql。

代码-

$('#tn1').click(function(){
          var msg='';
          alert('inside alert');
          if ($('textarea#message') != "") {
            var message = $('#notesarea').val();
            alert(message);
            msg=message;
          }


          $.ajax({
        url: 'post_note',
        data: {
          'note': msg
        },

        success: function (data) {
          alert(data)
        }
      });

views.py

def post_note(request,id):
    post_id = request.GET['note']
    print(post_id)
    //sql insertion code,once its done i want to notify to the front end..print some alert message.
    return render(request, './profile.html')

【问题讨论】:

    标签: python django ajax


    【解决方案1】:

    你应该在你的视图中使用类似 JSONResponse 的东西,然后你的数据就会出现在成功函数中

     success: function (data) {alert(data)}
    

    【讨论】:

      【解决方案2】:

      您可以在模板中使用 JQuery Ajax 并通过在您的 views.py 中创建一个“API 视图”来执行此操作,该视图基本上只是一个常规视图,在检查以验证请求是否为 Ajax 后返回 JSONResponse。作为“API”选项的示例,使用 JQuery:

      在您的 views.py 文件中(使用 GET 方法,只有在注释简短时才应使用该方法,它将适合 URL 栏,并且如果您没有重大安全问题,否则请参阅底部的 POST 示例):

          from django.http import JsonResponse
      
          def post_note_api(request):
                data = {}
                if request.GET.get('post_note', None) is not None:
                    post_note = request.GET.get('post_note')
                    # save the note and indicate success
                    data['result'] = True
                    data['message'] = "Note posted successfully"
                    ...
                if request.is_ajax():
                   return JsonResponse(data)
                else:
                   return HttpResponseBadRequest()
           
      

      在你的 urls.py 中:

      ...
      path('/api/post_note/', post_note_api, name="post_note_api"),
      ...
      

      在您的模板中(如果您使用的是 GET 方法):

        <script type="text/javascript">
      $("#tn1").click(function(){
          var message = $("#myTextArea").val();
          $.ajax({ url: '{% url 'post_note_api' %}?post_note=' + message,
                              type: "GET",
                              dataType: "json",
                              cache: false
                     }).done(function(data) {
                          if (data.result === true){
                              alert(data.message);
                         }
                     });
                });
             });
      </script>
      

      如果您使用的是 POST 方法而不是 GET(这可能是这里更好的选择):

      <script type="text/javascript">
              $("#tn1").click(function(){
                  var csrfToken = $( "input[name='csrfmiddlewaretoken']");
                  var message = $("#myTextArea").val();
                      $.ajax({ url: '{% url 'post_note_api' %}',
                                          type: "POST",
                                          dataType: "json",
                                          data: {'post_note':message, 'csrfmiddlewaretoken':csrfToken.val()},
                                          cache: false
                                 }).done(function(data) {
                                      if (data.result === true){
                                          alert(data.message);
                                     }
                                 });
                            });
                        });
                  </script>
      

      对于 POST 方法,在您看来,只需将 request.GET.get('post_note') ... 更改为 request.POST.get('post_note') ...,如下所示:

              from django.http import JsonResponse
      
              def post_note_api(request):
                    data = {}
                    if request.POST.get('post_note', None) is not None:
                        post_note = request.POST.get('post_note')
                        # save the note and indicate success
                        data['result'] = True
                        data['message'] = "Note saved successfully"
                        ...
                    if request.is_ajax():
                       return JsonResponse(data)
                    else:
                       return HttpResponseBadRequest()
      

      当您通过 POST 发送数据时,请不要忘记传递您的 CSRF 令牌,如上例所示。这假设您在页面上有一个可以从中获取它的表单,否则您可以使用类似的东西来获取它:

      function getCookie(name) {
          var cookieValue = null;
          if (document.cookie && document.cookie !== '') {
              var cookies = document.cookie.split(';');
              for (var i = 0; i < cookies.length; i++) {
                  var cookie = cookies[i].trim();
                  // Does this cookie string begin with the name we want?
                  if (cookie.substring(0, name.length + 1) === (name + '=')) {
                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                      break;
                  }
              }
          }
          return cookieValue;
      }
      var csrftoken = getCookie('csrftoken');
      

      如果你不想处理 CSRF 令牌,你可以用 @csrf_exempt 装饰器标记视图,并从模板中的 Ajax 调用中删除 'csrfmiddlewaretoken' 数据元素,但它可能不是理想的或最安全的。一个例子:

          from django.views.decorators.csrf import csrf_exempt
          from django.http import JsonResponse
      
          @csrf_exempt()
          def post_note_api(request):
                 ...
      

      现在,在不了解更多信息的情况下,这基本上只是伪代码(另外我只是在脑海中写下了这个,所以它可能有错误)。如果您发布更多详细信息,我可以更新我的答案,但我认为这应该让您开始。

      【讨论】:

      • 不刷新还是不更新。
      【解决方案3】:

      我在下面使用了将数据从 HTML 发送到 views.py,然后将成功响应返回给 HTML。希望这会有所帮助:)

      HTML 代码:

      <a href="{% url 'save' %}"><button class="button primary fit small" onclick="saveContent()">Save</button></a>
      

      Javascript 代码:

      <script>
      function saveContent(){
      var code =editor.getSession().getValue();
      var URL = "{% url 'save' %}";
      var data = {'code': code};
      $.post(URL, data, function(response){ // This is the main function that will help you
          if(response === 'success'){ window.location.reload(); }
          else{ alert('Error! :('); }
      });
      }
      </script>
      

      查看.py:

      def save_content(request):
          if request.method == 'POST':
              if 'code' in request.POST:
                  file_data = request.POST['code']
      
      return HttpResponse('success')
      

      【讨论】:

        猜你喜欢
        • 2021-10-18
        • 2017-08-10
        • 2013-06-22
        • 2015-11-07
        • 2014-10-01
        • 2020-10-08
        • 2021-08-21
        • 1970-01-01
        • 2018-07-13
        相关资源
        最近更新 更多