我正在尝试使用 ajax 提交登录表单。我对应该如何处理异常/成功响应感到困惑。我从服务器收到 200 OK,表单通过密码/用户名字段返回错误。如何获取错误消息以根据服务器响应显示或将用户重定向到适当的页面?
JQUERY:
56 $(window).load(function(){
57 $('#login_form').submit(function(e){
58 e.preventDefault();
59 var request_url = document.getElementById('next').value
60 $.ajax({
61 type:"POST",
62 url: $(this).attr('action'),
63 data: $('#login_form').serialize(),
64 success: function(response){ $('#msg').text(response);
65 console.log(response);
66 },
67 error: function(xhr, ajaxOptions, thrownError){ alert( $('#login_error').text('Username already taken. Please select another one.')},
68 });
69 });
70 });
View :已更新
51 def login(request):
52 if request.method == 'POST':
53 request.session.set_test_cookie()
54 login_form = AuthenticationForm(request, request.POST)
55 if login_form.is_valid():
56 if request.is_ajax:
57 user = django_login(request, login_form.get_user())
58 if user is not None:
59 return HttpResponseRedirect(request.REQUEST.get('next', '/'))
**else:**
61 **return HttpResponseForbidden() # catch invalid ajax and all non ajax**
60 else:
61 login_form = AuthenticationForm(request)
62
63 c = Context({
64 'next': request.REQUEST.get('next'),
65 'login_form': login_form,
66 'request':request,
67 })
68 return render_to_response('login.html', c, context_instance=RequestContext(request))
表格:
7 <tt id="login_error"></tt>
8 <form id="login_form" action="" method="post">
9
10 {{ login_form }}
11 <input type="submit" value="login"/>
12 <input type="hidden" id="request_path" name="next" value="/"/>
13 </form>
14 <p>{{ request.get_full_path }}</p>
15 <tt id='msg'></tt>
最佳答案
虽然使用 json 执行此操作肯定是更好的做法,但您可以不用,假设您没有真正从服务器传回太多信息。在 django 端,将 HttpResponseRedirect 换成 HttpResponse,使用重定向 URL 作为您的消息。还添加一个 HttpResponseForbidden 用于 ajax 登录失败的情况。
def login(request):
if request.method == 'POST':
request.session.set_test_cookie()
login_form = AuthenticationForm(request, request.POST)
if login_form.is_valid():
if request.is_ajax:
user = django_login(request, login_form.get_user())
if user is not None:
return HttpResponse(request.REQUEST.get('next', '/'))
return HttpResponseForbidden() # catch invalid ajax and all non ajax
else:
login_form = AuthenticationForm()
c = Context({
'next': request.REQUEST.get('next'),
'login_form': login_form,
'request':request,
})
return render_to_response('login.html', c, context_instance=RequestContext(request))
然后在 javascript 端,检查响应的状态代码。如果它是 200,那么这就是您的 HttpResponse - 您想要重定向到响应消息中的 url。如果是 403,那么就是您的 HttpResponseForbidden - 登录失败。您可以摆脱标准的“登录失败”错误消息。
$.ajax({
type:"POST",
url: $(this).attr('action'),
data: $('#login_form').serialize(),
// the success function is called in the case of an http 200 response
success: function(response){
// redirect to the required url
window.location = response;
},
error: function(xhr, ajaxOptions, thrownError){
alert('login failed - please try again');
},
});
恐怕我还没有测试过这个,但它应该会给你一个想法。
有关更多信息,请查看 docs for django's HttpResponse objects .然后查看 jquery ajax docs .
关于javascript - Django Ajax 登录表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13784136/
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的
我在事件管理员编辑页面中有嵌套资源,但我只想允许管理员编辑现有资源的内容,而不是添加新的嵌套资源。我的代码看起来像这样:formdo|f|f.inputsdof.input:authorf.input:contentf.has_many:commentsdo|comment_form|comment_form.input:contentcomment_form.input:_destroy,as::boolean,required:false,label:'Remove'endendf.actionsend但它在输入下添加了“添加新评论”按钮。我怎样才能禁用它,并只为主窗体保留f.ac
我需要从站点抓取数据,但它需要我先登录。我一直在使用hpricot成功地抓取其他网站,但我是使用mechanize的新手,我真的对如何使用它感到困惑。我看到这个例子经常被引用:require'rubygems'require'mechanize'a=Mechanize.newa.get('http://rubyforge.org/')do|page|#Clicktheloginlinklogin_page=a.click(page.link_with(:text=>/LogIn/))#Submittheloginformmy_page=login_page.form_with(:act
我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan
我目前正在尝试将ERB布局转换为HAML。这是我不断收到的错误:index.html.haml:18:syntaxerror,unexpected')'));}\n#{_hamlout.format_...这是HAML页面:.row-fluid.span6%h2TodoList.span6%h2{:style=>"text-align:right;"}document.write(today)%hr.divider.row-fluid.span6%h2.small_headNewTask=render:partial=>'layouts/form_errors',:locals=>{:
为现有模型生成单个文件(_form.html.erb)的命令是什么?在Rails3中工作。谢谢。 最佳答案 这听起来可能很傻,但请听我说完……当我想开始清洁时,我自己也做过几次这样的事情。以下是一个脚本,它将读取您的模式并生成必要的生成命令来重现它:require'rubygems'require'active_support/core_ext'schema=File.read('db/schema.rb')schema.scan(/create_table"(\w+)",.*?\n(.*?)\nend/m).eachdo|name
我不想显示表单,但前提是当前页面不是主页这是我目前所拥有的...我有我的路线设置:root'projects#index'我的看法:'projects',:action=>'index'))%>showsomestuff如果url是localhost:3000/projects,则不会显示但是它显示了它的localhost:3000所以我需要以某种方式确保它不会显示主页。另外,我有主页的搜索参数,但我仍然不想显示它是否像localhost:3000/projects?search=blahblahblah 最佳答案 使用root_p
我为Devise用户和管理员提供了不同的模型。我也在使用Basecamp风格的子域。除了我需要能够以用户或管理员身份进行身份验证的一些Controller和操作外,一切都运行良好。目前我有authenticate_user!在我的application_controller.rb中设置,对于那些只有管理员才能访问的Controller和操作,我使用skip_before_filter跳过它。不幸的是,我不能简单地指定每个Controller的身份验证要求,因为我仍然需要一些Controller和操作才能被用户或管理员访问。我尝试了一些方法都无济于事。看来,如果我移动authentica