Ajax提交数据时候,携带CSRF:
a. 放置在data中携带

<form method="POST" action="/csrf1.html">
    {% csrf_token %}
    <input  />
    <input type="submit" value="提交"/>
    <a onclick="submitForm();">Ajax提交</a>
</form>
<script src="/static/jquery-1.12.4.js"></script>
<script>
    function submitForm(){
        var csrf = $('input[name="csrfmiddlewaretoken"]').val();
        var user = $('#user').val();
        $.ajax({
            url: '/csrf1.html',
            type: 'POST',
            data: { "user":user,'csrfmiddlewaretoken': csrf},
            success:function(arg){
                console.log(arg);
            }
        })
    }

</script>
                
b. 放在请求头中
            
<form method="POST" action="/csrf1.html">
    {% csrf_token %}
    <input  />
    <input type="submit" value="提交"/>
    <a onclick="submitForm();">Ajax提交</a>
</form>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script>

<script>
    function submitForm(){
        var token = $.cookie('csrftoken');
        var user = $('#user').val();
        $.ajax({
            url: '/csrf1.html',
            type: 'POST',
            headers:{'X-CSRFToken': token},
            data: { "user":user},
            success:function(arg){
                console.log(arg);
            }
        })
    }
</script>

 

相关文章:

  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
  • 2022-01-10
  • 2022-02-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-20
  • 2021-09-24
  • 2021-09-24
  • 2022-12-23
  • 2021-07-11
  • 2021-12-16
相关资源
相似解决方案