![](/img/trans.png)
[英]Sending E-Mail with multiple attachments and JavaScript Ajax request
[英]Existing E-mail check (Django + Javascript/Ajax)
我一直在尝试用 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>
我可能跳过了一些步骤,你能帮我理解它们是哪些吗?
谢谢!
从$.ajax()
删除以下参数
dataType: "json",
contentType: "application/json",
它会起作用。
我在本地对其进行了测试,当内容类型为application/json
它似乎无法按预期工作。 也许 django 期望内容类型为application/x-www-form-urlencoded
以用于 POST 请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.