weixin_33698043 2017-09-19 13:23 采纳率: 0%
浏览 51

Django 403禁止错误

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条回答 默认 最新

  • weixin_33725272 2017-09-19 14:08
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 vscode里面怎么用plaformio强调串口啊
  • ¥20 针对计算后数据做一致性检验可以用Bland Altman法吗
  • ¥15 win32如何自绘编辑框的背景图片(语言-c++|操作系统-windows)
  • ¥15 微信夜间被转走了1w对,当天手机剪切板里就出现了这个乱码,有铁子可以看看是啥吗可以
  • ¥50 跑通github上的代码 深度学习 pytorch
  • ¥50 求写,批处理调用分区助手分区脚本
  • ¥15 求购HI3519AV100开发板
  • ¥15 请问1553 RT怎么测试,没有BC有方法吗
  • ¥15 wamp3.3.5安装完成后图标正常显示绿色,鼠标左右键点击图标均无反应。求解决方法。
  • ¥15 鼠标点击的这条记录了什么?