django通过ajax发起请求返回JSON格式的数据
这是后台处理的
def checkemail(request): user = None if request.POST.has_key('email'): useremail = request.POST['email'] result = {} user = User.objects.filter(useremail__iexact = useremail) if user: result = "1" result = simplejson.dumps(result) else: result = "0" result = simplejson.dumps(result) return HttpResponse(result, mimetype='application/javascript')
这是AJAX部分
if(valid_email($('#reg-for-email').val())){ var email = $('#reg-for-email').val(); //这里把用户输入的EMAIL地址提交到后台数据库中去验证是否已存在。 $.ajax({ type:"POST" , url:"/reg/checkemail", data:"email=" + email , cache: false, success: function(result){ if (result==1) { $("#reg-for-email-msg").removeClass("g-hide"); $('#reg-for-email-msg').removeClass("msg-isok").addClass("msg-error").html("该邮箱已存在!"); eok = true; } else { $("#reg-for-email-msg").addClass("g-hide"); eok = false; } } }) }
URL的配置是:
url(r'^reg/checkemail/', 'reg.views.checkemail', name='ce'),