Django 403 Forbidden Error

落爺英雄遲暮 提交于 2019-12-13 07:25:54

问题


When I try the ajax in same page to html it works. Like this;

<html>
    <head>
     ...
    </head>
    <body>
     ....
     <script>

    $.ajax({
        url: /test/,
        method: 'POST',
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
        data: { name: a, surname: b},
        dataType: 'json',
        success: function (data) {
            getList(data);
        }
    });
    </script>
  </body>
</html>

When I try the call same javascript as external. It doesn't work. Why?

<html>
    <head>
     ...
    </head>
    <body>
     ....
     <script src="{% static 'js/test.js' %}"></script>
  </body>
</html>

回答1:


Define the {{ csrf_token }} as a global variable in your HTML page in script tag as a global variable as such:-

var generated_csrf_token = "{{ csrf_token }}";

And then in your .js file call it,

headers: {'X-CSRFToken': generated_csrf_token},

But make sure you put AJAX call within the document ready func in $(document).ready(function () {***here***}

This way you can access it with name generated_csrf_token in any js file.

Hope this helps :-)



来源:https://stackoverflow.com/questions/46301675/django-403-forbidden-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!