2010-05-28 91 views
20

我是ajax的新手,我知道有人會遇到這個問題。 我有一個構建在Spring MVC上的傳統應用程序,它有一個攔截器(過濾器),用於在沒有會話時將用戶重定向到登錄頁面 頁面。在Ajax jquery調用上重定向

public class SessionCheckerInterceptor extends HandlerInterceptorAdapter { 
public boolean preHandle(HttpServletRequest request, 
    HttpServletResponse response, Object handler) throws Exception { 
    HttpSession session = request.getSession(); 

    // check if userInfo exist in session 
    User user = (User) session.getAttribute("user"); 
    if (user == null) { 
    response.sendRedirect("login.htm"); 
    return false; 
    } 
    return true; 
} 
} 

對於非XMLHTTP請求,這工作正常..但是當我嘗試在我的應用程序中使用AJAX,一切變得怪異, 它不能夠正確地重定向到登錄頁面。 作爲檢查

xhr.status = 200 textStatus = parseError errorThrown =「無效的JSON我的HTML登錄的-Markup的頁面 - 我查了我的螢火蟲,有一個302的價值

$(document).ready(function(){ 
     jQuery.ajax({ 
      type: "GET", 
      url: "populateData.htm", 
      dataType:"json", 
      data:"userId=SampleUser", 
      success:function(response){ 
      //code here 
      }, 
     error: function(xhr, textStatus, errorThrown) { 
       alert('Error! Status = ' + xhr.status); 
      } 

     }); 
}); 

HTTP響應,但我在這裏我不知道如何捕捉到的響應和用戶重定向到登錄 頁面。任何想法?謝謝。

回答

47

jQuery是尋找一個JSON類型的結果,但由於重定向自動處理,它會收到生成了您的login.htm頁面的html源代碼

一個想法是讓瀏覽器知道它應該通過增加一個redirect變量所得到的對象和JQuery的檢查重定向:

$(document).ready(function(){ 
    jQuery.ajax({ 
     type: "GET", 
     url: "populateData.htm", 
     dataType:"json", 
     data:"userId=SampleUser", 
     success:function(response){ 
      if (response.redirect) { 
       window.location.href = response.redirect; 
      } 
      else { 
       // Process the expected results... 
      } 
     }, 
    error: function(xhr, textStatus, errorThrown) { 
      alert('Error! Status = ' + xhr.status); 
     } 

    }); 
}); 

你也可以添加一個頭變到你響應並讓您的瀏覽器決定重定向的位置。在Java中,而不是重定向,做response.setHeader("REQUIRES_AUTH", "1")和JQuery的你成功做(!):

//.... 
     success:function(response){ 
      if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
       window.location.href = 'login.htm'; 
      } 
      else { 
       // Process the expected results... 
      } 
     } 
//.... 

希望有所幫助。

我的回答很大程度上受this thread的啓發,如果您仍有問題,請不要留下任何問題。

+0

嗨moonground ..謝謝,我想我已經得到你的觀點已經給出這個例子...非常感謝你... – 2010-05-31 01:18:45

+0

謝謝托馬斯。我有點得到它,但我會讀更多的參考線程,所以它可以沉入一點。儘管如此,它似乎是我正在尋找的答案,所以非常感謝! – Mark 2012-11-01 16:47:23

+1

如何將重定向變量添加到響應中? – nikli 2015-06-08 06:31:04