$ ajax命令和Json响应 [英] $ajax command and Json response
问题描述
在我的django应用程序中,我尝试使用ajax来检查用户名是否已经存在,如果是这样的话会显示错误。
In my django app I try to use ajax in order to check if a username already exists and display an error if it is the case.
这是我的有
html:
<form method="post" id='my_form'>
{% csrf_token %}
<input id='username' type="text" name="username"/>
<button type="submit">Valider</button>
</form>
js:
$('#my_form').submit(function(){
var username = $('#username').val();
if (username == ''){
alert('please enter username');
return false;
}
$.ajax({
type: "POST",
url: "/auth_validate",
data: {'username': $('#username').val(), 'csrfmiddlewaretoken': '{{csrf_token}}'},
dataType: "text",
success: function(response) {
var response = $.parseJSON(response);
if (response.success){
return true;
}
else{
alert(response.error);
return false;
}
},
error: function(rs, e) {
alert(rs.responseText);
return false;
}
});
})
意见:
def auth_validate(request):
error = ''
success = False
if request.method == 'POST':
username = request.POST.get('username', None)
if not username:
error = _('Please enter username')
elif User.objects.filter(username__exact=username).exists():
error = _('Sorry this username is already taken')
else:
success = True
ajax_vars = {'success': success, 'error': error}
return HttpResponse(simplejson.dumps(ajax_vars), mimetype='application/javascript')
当我输入用户名(如果存在或不存在)时,会出现一个空的警告,当我点击确定时,表单被提交。
此外,错误不会出现。
When I enter a username (if it exists or not) an empty alert appears and when I click on 'ok', the form is submitted. Moreover, the errors do not appear.
任何想法为什么它不起作用?
Any idea on why it doesn't work?
谢谢你的帮助。
推荐答案
你的视图和模板看起来很好
我建议你使用本机 JSON
处理函数具有并序列化窗体,而不是手动发送数据
。还请注意事件回调结束时的 return false
,而不是在成功
和错误
回调。
Your view and template look fine
I suggest that you use the native JSON
handling the function has and serialize the form instead of "sending" data
manually. Also please note the return false
at the end of the event callback, instead of inside the success
and error
callbacks.
$('#my_form').on('submit', function(){
var $form = $(this);
$.ajax({
type: "POST",
url: "/auth_validate",
data: $form.serialize(),
dataType: "json",
success: function(response) {
if (!response.success) {
alert(response.error);
} else {
alert('This username is available!');
}
},
error: function(rs, e) {
alert(rs.responseText);
}
});
return false;
});
祝你好运:)
更新:
请检查成功回调中的else);
Please check the else in the success callback ;)
这篇关于$ ajax命令和Json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!