繁体   English   中英

通过 Ajax 将数据从 Django 模板发送到 views.py

[英]Sending data from a Django template to views.py via Ajax

我正在通过 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)
        }
      });

视图.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')

您应该在视图中使用 JSONResponse 之类的东西,然后您的数据将成功显示 function

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

您可以在模板中使用 JQuery Ajax 并在您的 views.py 中创建一个“API 视图”,该视图基本上只是一个常规视图,在检查以验证请求是否为JSONResponse后返回 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):
           ...

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

我在下面使用了将数据从 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM