1

我试图在网站上实现一个按钮,按下它后会自动在服务器上运行一个 python 函数并将一些值复制到用户的剪贴板中。剪贴板复制运行良好,但我无法运行 python 函数。

每当我尝试时,我都会收到错误 403,我认为这是由于 csfr 令牌的问题。谁能帮我解决这个问题?

这是我的 HTML

{% if categories %}
<div class="card shadow mb-4">

    <div class="card-body card-interface">

        <table id="predictionTable" class="table table-bordered">
            <thead>
                <tr>
                    <th>Vorhersage</th>
                    <th>Wahrscheinlichkeit</th>
                    <th>Kopieren</th>
                </tr>
            </thead>
            <tbody>
            {% for category in categories %}
            <tr>
                <td>{{ category.0}}</td>
                <td>{{ category.1}}%</td>
                <td><img src="{% static "documents/img/copy.png" %}" class="interface-copy" value="{{ category.0 }}" input_text = "{{ input_text }}" style="cursor: pointer"></td>
            </tr>
            {% endfor %}
            </tbody>
        </table>

    </div>
</div>
<div id="django-data" data-CSRF="{{csrf_token}}"></div>

这里是运行的 .js

  $(".interface-copy").on('click', function(e) {

    var csrftoken = $("django-data").data().CSRF;
    console.log(csrftoken);
    console.log("test")
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(this).attr('value')).select();
    document.execCommand("copy");
    $temp.remove();
    console.log("test")
    $.ajax({
      url: "/ajax/postSingleSourceEntry/",
      type : 'POST',
      beforeSend: function(request){
        request.setRequestHeader("X-CSRFToken", csrftoken);
      },
      data: {
        csfrmiddlewaretoken: csrftoken
      },
      dataType: "json",
      success: function (data){
        console.log("call created")
      },
      error : function(response){
        console.log(response)
      }
    })
  });
4

2 回答 2

0

改变:

<div id="django-data" data-CSRF="{{csrf_token}}"></div>

至:

<div id="django-data" data-csrf="{{csrf_token}}"></div>

和:

var csrftoken = $("django-data").data().CSRF;

至:

var csrftoken = $("#django-data").data().csrf;    // Note the # before django-data and csrf in small letter.

您可能想阅读:如何获取 data-id 属性?

于 2020-02-04T06:26:45.970 回答
0

@csrf_exempt您可以为该 ajax 函数添加装饰器

于 2020-02-04T06:38:02.640 回答