我一直在尝试使用Django和Javascript / Ajax构建一个电子邮件验证器,但我一直困扰着。我得到了Ajax响应
{response: "This field is required.", email: false}
email: false
response: "This field is required."
但即使我填写了电子邮件字段,它也总是一样的。
这是我的 view.py
@requires_csrf_token
def email_check(request):
email = request.POST.get('email', False)
if request.is_ajax():
if email:
query_email = CustomUser.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')
这是模板和脚本
<form>
{% csrf_token %}
<input id="email" type="email" name="email">E-mail</a>
</form>
<script type="text/javascript">
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() {
$("#email").focusout(function(e) {
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var email = $('#email').val();
$.ajax({
url: "/email_check/",
type: "POST",
dataType: "json",
contentType: "application/json",
data : {
csrfmiddlewaretoken: csrftoken,
email: email
},
success: function(result) {
console.log(result);
},
});
});
});
</script>
我可能会跳过一些步骤,你能帮我理解它们是什么吗?
谢谢!
答案 0 :(得分:1)
从$.ajax()
dataType: "json",
contentType: "application/json",
它会起作用。
我在本地测试了它,当内容类型为application/json
时,它似乎没有按预期工作。也许django期望POST请求的内容类型为application/x-www-form-urlencoded
。