AJAX无法使用Django App

时间:2014-09-16 12:26:04

标签: javascript jquery python django django-templates

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-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成功并不起作用。

1 个答案:

答案 0 :(得分:1)

这是一个CSRF令牌问题。你发送了csrftoken cookie吗?去那里https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#csrf-ajax以了解附加内容并从Django网站复制/粘贴此javascript代码:

// 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);
        }
    }
});