Skip to main content
 首页 » 编程设计

jquery之从 AJAX 调用返回 render_to_response

2024年10月24日39kerrycode

所以我使用 ajax 调用来让用户登录网站。具体来说,如果登录无效,我将使用 ajax 以模式显示消息。现在,如果登录确实有效,那么我将使用 python 的 render_to_response 将用户重定向到他各自的主页。但是,现在用户已经登录,他们不会被重定向到他们的主页。我猜这是因为我不是从 ajax 调用中进行的。我想知道这周围是否有任何东西? 这是 View :

def login(request): 
    # After login Create class can be called 
    if request.POST.get('class_id'): 
        return create_class(request) 
 
    if request.POST.get('email'): 
        email = request.POST.get('email') 
        password = request.POST.get('password') 
        user = auth.authenticate(email=email, password=password) 
 
    elif request.session['_auth_user_id']: 
        # Instructors Current class and course will be generated on pageload 
        sem = get_semester 
        year = datetime.now().year 
        return render_to_response('home.html', {'sem':sem, 'year':year, 
        'inscourses':instructors_current_courses_classes(request), 
        'student_class_status':student_current_class_status(request), 
        'courses':allCourses()}, context_instance=RequestContext(request)) 
 
    if user is not None: 
        auth.login(request, user) 
        # Instructors Current class and course will be generated on pageload 
        sem = get_semester 
        year = datetime.now().year 
        return render_to_response('home.html', {'sem':sem, 'year': year, 
        'inscourses': instructors_current_courses_classes(request), 
        'student_class_status': student_current_class_status(request), 
        'courses': allCourses()}, context_instance=RequestContext(request)) 
    else: 
        return HttpResponse(json.dumps(True),content_type = 'application/json') 

这是ajax调用:

<script type = "text/javascript">  
  function login(){ 
    $.ajax({ 
      type : "POST", 
      url  : "http://localhost:8000/User/home", 
      dataType : "json", 
      async : true, 
      data : { 
        csrfmiddlewaretoken : '{{ csrf_token }}', 
        email : $('#emailInput').val(), 
        password: $('#passwordInput').val() 
 
      }, 
 
      success:function(){ 
        $('#loginError').css("visibility", "visible");           
      }, 
      error:function(){ 
        console.log("failed"); 
      } 
 
    }); 
 
  }    
</script> 

请您参考如下方法:

当您从 ajax 处理程序返回某些内容时,它以 success 处理程序结束:

success: function (data) { 
    // data here is a chunk of HTML from render_to_response() 
} 

更糟糕的是,由于您设置了 dataType: json jQuery 将尝试将此 HTML 解码为 JSON 并失败,我不知道接下来会发生什么。

你应该明白几件事:

  • 任何对 Ajax 请求的响应都不会被渲染,而是被解码并传递给 success 处理程序,
  • 如果您正在处理 Ajax 请求,则不能从服务器端重定向,
  • 如果您在一种情况下传递 JSON(user is None),那么您应该始终传递 JSON。

所以你可以通过两种方式解决这个问题。首先 - 不要使用 Ajax 登录,使用普通登录,无论如何你都会在登录时重定向,所以它不会向你的网站添加任何内容。

如果出于某种原因您仍想使用 Ajax 登录,请使用类似的方法:

if user is not None: 
    # ... 
    return JsonResponse({'success': True}) 
else: 
    return JsonResponse({'success': False, 'message': '...'}) 

还有:

  success: function(res) { 
      if (res.success) window.location.href = '/home'; 
      else showError(res.message); 
  }, 
  error: function() { 
      showError('Failed to connect to server. Please try later.'); 
  }