我正在进行如下所述的ajax调用。我正在开发一个简单的取消订阅表单,用户可以在其中输入电子邮件并从邮件提醒中取消订阅。 使用django框架
<html>
<head>
<script src="https://code.jquery.com/jquery.min.js" ></script>
</head>
<body>
<div id="errorDiv"></div>
<form id="unsubscribeform" class="unsubscribeform" method="POST" action="{% url 'polls:unsubscribe' %}" enctype="multipart/form-data">
{% csrf_token %}
<label class="required" for="emailUnsubscription">Email</label>
<input id="emailUnsubscription" name="unsubscribeEmail" type="email"><br><br>
<input value="unsubscribe" class="submit" id="submit" type="submit"/>
</form>
<script>
$(document).ready(function()
{
$('.submit').bind('click', function(event)
{
event.preventDefault();
var form_data = new FormData($(".unsubscribeform")[0]);
$.ajax({
type: 'POST',
url:"?ajax=1",
data:form_data,
processData: false,
contentType: false,
success:function(response)
{
var resp = response;
var noUserError = response.nouser;
var emptyEmailError = response.emptyemail;
if(typeof emptyEmailError === 'undefined' && typeof noUserError === 'undefined'){
$(.submit).unbind('click').submit();
}else{
if(typeof emptyEmailError === 'undefined')
emptyEmailError = "";
if(typeof noUserError === 'undefined')
noUserError = "";
$(".errorlist").remove();
console.log(noUserError, emptyEmailError);
$("errorDiv").append('<span class="errorlist"><br>'+Please correct following errors+'</span>');
$("errorDiv").append('<span class="errorlist"><br>'+noUserError+'</span>');
$("errorDiv").append('<span class="errorlist"><br>'+emptyEmailError+'</span>');
}
}
});
});
});
</script>
</body>
在html中成功返回我的表单后迷路了,我只得到了一个返回json的普通html。
在ajax调用
之后,浏览器中会显示以下文本{"nouser": "No user exists with given email id"}
我在这里做错了什么
答案 0 :(得分:2)
您需要将代码更新为以下
$('.submit').bind('click', function(event) {
event.preventDefault();
....
});