简体   繁体   English

Django 403禁止错误

[英]Django 403 Forbidden Error

When I try the ajax in same page to html it works. 当我在同一页面中尝试将ajax转换为html时,它可以工作。 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. 当我尝试调用相同的JavaScript作为外部。 It doesn't work. 没用 Why? 为什么?

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

Define the {{ csrf_token }} as a global variable in your HTML page in script tag as a global variable as such:- script标签的HTML页面中,将{{ csrf_token }}定义为全局变量,例如:

var generated_csrf_token = "{{ csrf_token }}";

And then in your .js file call it, 然后在您的.js文件中调用它,

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

But make sure you put AJAX call within the document ready func in $(document).ready(function () {***here***} 但是请确保在$(document).ready(function () {***here***}

This way you can access it with name generated_csrf_token in any js file. 这样,您可以在任何js文件中使用名称generated_csrf_token访问它。

Hope this helps :-) 希望这可以帮助 :-)

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

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