简体   繁体   中英

Django 403 Forbidden Error

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>

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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