AJAX不能使用Django App [英] AJAX not working with Django App
本文介绍了AJAX不能使用Django App的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
mysite / urls.py :
from mysite import views
url(r'^checkhandles/$', views.checkhandles, name='checkhandles'),
mysite / views.py :
def checkhandles(request, email):
if request.is_ajax():
message = 'Yes, I am reachable!'
else:
message = 'No, I am not reachable!'
return HttpResponse(message)
mysite-ajax.js :在DOM上准备好/ p>
mysite-ajax.js: on DOM-ready.
$(document).on('blur', '#email', function(){
var $this = $( this );
var email = $this.val();
if (validateEmail(email) === true){
alert(email);
var request = $.ajax({
url: "/mysite/checkhandles/",
type: "POST",
data: { email : email },
dataType: "json"
});
request.done(function( msg ) {
alert( msg );
//$(".email_details").html( msg );
//$(".email_etails").slideDown(150);
});
};
})
我该如何工作?只有 alert(email)
和 alert(msg)
可以告诉你可以告诉AJAX是不成功的。
How do I this work? It only alert(email)
and alert(msg)
that can tell that can tell AJAX was successful doesn't work.
推荐答案
这是一个CSRF令牌问题。发送 csrftoken
cookie?前往 https://docs.djangoproject.com/en/ dev / ref / contrib / csrf /#csrf-ajax 了解从Django网站追加并复制/粘贴此JavaScript代码:
It's a CSRF token problem. Do you send the csrftoken
cookie ? Go there https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#csrf-ajax to understand what appends and copy/paste this javascript code from Django web site :
// 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');
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);
}
}
});
这篇关于AJAX不能使用Django App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文