Ajax Jquery 호출 시 리디렉션
저는 여기 아약스에 처음 온 사람이고 누군가가 이미 이 문제에 직면했을 것이라는 것을 알고 있습니다.Spring MVC 기반의 레거시 앱이 있는데 세션이 없을 때마다 사용자를 로그인 페이지로 리디렉션하는 인터셉터(필터)가 있습니다.
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 오류던짐 = "Invalid JSON -Markup of my HTML Login Page-
$(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);
}
});
});
파이어버그에서 302 HTTP 응답이 있다고 확인했는데 응답을 잡고 사용자를 로그인 페이지로 리디렉션하는 방법을 잘 모르겠습니다.무슨 생각 있어요?감사해요.
JQuery는 json 유형의 결과를 찾고 있지만 리디렉션이 자동으로 처리되므로 생성된 html 소스를 수신합니다.login.htm페이지입니다.
하나의 아이디어는 브라우저가 a를 추가하여 리디렉션해야 한다는 것을 알려주는 것입니다.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...
}
}
//....
도움이 되길 바랍니다.
제 대답은 이 스레드에서 영감을 많이 받은 것입니다. 이 스레드는 여전히 문제가 있을 경우 질문을 남겨서는 안 됩니다.
ExpressJs 라우터의 경우:
router.post('/login', async(req, res) => {
return res.send({redirect: '/yoururl'});
})
클라이언트 측:
success: function (response) {
if (response.redirect) {
window.location = response.redirect
}
},
언급URL : https://stackoverflow.com/questions/2927044/redirect-on-ajax-jquery-call
'programing' 카테고리의 다른 글
| 핵심 데이터: 경고:명명된 클래스를 로드할 수 없습니다. (0) | 2023.10.26 |
|---|---|
| 오류 코드: 1055가 sql_mode=only_full_group_by와 호환되지 않음 (0) | 2023.10.26 |
| virtualenv(python3.4), pip install mysql 클라이언트 오류 (0) | 2023.10.26 |
| 워드프레스: 알파벳순으로 previor_post_link / next_post_link? (0) | 2023.10.26 |
| 모든 카테고리에서 랜덤으로 2개 레코드 선택 그룹 in MariaDB (0) | 2023.10.26 |