在Javascript中返回JSON响应(来自Django视图)

时间:2016-03-14 13:31:49

标签: javascript jquery json ajax django

当我输入电子邮件字段时,我正试图在AJAX中获取JSON响应。 我在控制台上得到了响应,比如

{response: "example@gmail.com is already in use.", email: "example@gmail.com"}
email: "example@gmail.com"
response:"example@gmail.com is already in use."

{response: "This field is required..", email: ""}
email: ""
response:"This field is required."

但我不知道如何将响应用作Javascript值。我想使用它来自动发送消息,告知电子邮件是否可用。

这是我到现在为止所得到的 我的模板 + 脚本

<form data-parsley-validate id="form" method="post" action="/register/" enctype="multipart/form-data">

{% csrf_token %}

{{ form.as_p }}
<p id="email-error"></p>

<input type="submit" id="submit" class="btn btn-info" name="submit" value="Register" />
</form>

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

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
            // Only send the token to relative URLs i.e. locally.
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});


$(document).ready(function() {
    $("#id_email").focusout(function(e) {
        e.preventDefault();
        var csrftoken = getCookie('csrftoken');
        var email = $('#id_email').val();

        $.ajax({
            url: "/email_check/",
            type: "POST",            
            dataType: "json",
            data : { 
                csrfmiddlewaretoken: csrftoken, 
                email: email
            },
            success: function(result) {
                document.getElementById("email-error").innerHTML = result;
            },
        });
    });
});
</script>

view.py

@requires_csrf_token
def email_check(request):
    email = request.POST.get('email', False)
    if request.is_ajax():
        if email:
            query_email = User.objects.filter(email=email)
            if query_email.exists():
                res = "{0} is already in use.".format(email)
            else:
                res = "This E-mail is ok."
            ajax_vars = {'response': res, 'email': email}
            json_data = json.dumps(ajax_vars)
        else:
            res = "This field is required."
            ajax_vars = {'response': res, 'email': email}
            json_data = json.dumps(ajax_vars)

        return HttpResponse(json_data, content_type='application/json')

使用此代码,我回复“#email-error”的消息是: [object Object]
我错过了什么?

谢谢!

0 个答案:

没有答案