AJAX not working with Django App

妖精的绣舞 提交于 2019-12-11 22:13:53

问题


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

How do I this work? It only alert(email) and alert(msg) that can tell that can tell AJAX was successful doesn't work.


回答1:


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


来源:https://stackoverflow.com/questions/25868726/ajax-not-working-with-django-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!