<p>尝试此代码</p>
<pre><code>// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var query = {
"text": "My input statement",
"csrfmiddlewaretoken": csrftoken
};
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8000/chatterbot/",
data: query,
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});
</code></pre>
<p>一种方法是像下面这样发送<code>csrfmiddlewaretoken</code></p>
<pre><code> var query = {
"text": "My input statement",
'csrfmiddlewaretoken': "{{csrf_token }}"
};
</code></pre>
<p>另一种方法是使用<code>@csrf_exempt</code>装饰器</p>
<pre><code> from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def IndexView(request):
# .... code.....
</code></pre>
<p>另一种是添加脚本</p>
<pre><code>function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</code></pre>
<p>引用:<a href="https://docs.djangoproject.com/en/2.0/ref/csrf/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.0/ref/csrf/</a></p>