다른 웹 페이지로 리디렉션하려면 어떻게 해야 합니까?

jQuery 또는 순수 JavaScript를 사용하여 사용자를 한 페이지에서 다른 페이지로 리디렉션하려면 어떻게 해야 합니까?



질문에 대한 답변



단순히 jQuery를 사용하여 리다이렉트하는 것이 아닙니다.

jQuery는 필요하지 않으며 HTTP 리다이렉트를 가장 잘 시뮬레이트합니다.

window.location.replace(...)사용하는 것보다 낫다window.location.href,왜냐면replace()는 세션 이력에 원래 페이지를 유지하지 않기 때문에 사용자는 끝없는 백버튼의 실패에 빠지지 않습니다.

링크를 클릭하는 것을 시뮬레이트하려면

HTTP 리다이렉트를 시뮬레이트하려면

예를 들어 다음과 같습니다.

// similar behavior as an HTTP redirect window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link window.location.href = "http://stackoverflow.com"; 



경고: 이 답변은 가능한 해결책으로 제공되었을 뿐입니다.jQuery가 필요하기 때문에 최적의 솔루션은 아닙니다.대신 순수 JavaScript 솔루션을 선호합니다.

$(location).prop('href', 'http://stackoverflow.com') 



페이지를 리다이렉트하기 위한 표준 “vanilla” JavaScript 방법

window.location.href = 'newPage.html'; 

또는 더 간단하게: (이후)window글로벌)

location.href = 'newPage.html'; 

리다이렉트 중에 HTTP_REFERER가 손실되어 있는 경우는, 다음의 내용을 참조해 주세요.

(그렇지 않으면 이 마지막 부분을 무시합니다.)


다음 섹션은 다음을 사용하는 사용자를 대상으로 합니다.HTTP_REFERER많은 보안 조치 중 하나로 사용됩니다(비록 훌륭한 보호 조치는 아니지만).Internet Explorer 8 이하 버전을 사용하는 경우, 모든 형식의 JavaScript 페이지 리디렉션(위치)을 사용하면 이러한 변수가 손실됩니다.href 등).

이하에서는, HTTP_REFERER를 잃지 않기 위해서 IE8 이하의 대체품을 실장합니다.그렇지 않으면, 거의 항상 간단히 사용할 수 있습니다.window.location.href.

에 대한 테스트HTTP_REFERER(URL 붙여넣기, 세션 등)을 사용하면 요청이 합법적인지 여부를 확인할 수 있습니다.(주의: 코멘트의 드롭 링크에서 알 수 있듯이, 이러한 레퍼러를 회피하거나 스푸핑하는 방법도 있습니다.)


간단한 크로스 브라우저 테스트 솔루션(window.location으로 폴백).href (Internet Explorer 9+ 및 기타 모든 브라우저용)

사용방법:redirect('anotherpage.aspx');

function redirect (url) {
var ua
= navigator.userAgent.toLowerCase(),
isIE
= ua.indexOf('msie') !== -1,
version
= parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
} } 



이렇게 하는 방법은 여러 가지가 있습니다.

// window.location window.location.replace('http://www.example.com') window.location.assign('http://www.example.com') window.location.href = 'http://www.example.com' document.location.href = '/path'
// window.history window.history.back() window.history.go(-1)
// window.navigate; ONLY for old versions of Internet Explorer window.navigate('top.jsp')
// Probably no bueno self.location = 'http://www.example.com'; top.location = 'http://www.example.com';
// jQuery $(location).attr('href','http://www.example.com') $(window).attr('location','http://www.example.com') $(location).prop('href', 'http://www.example.com') 



이는 모든 브라우저에서 작동합니다.

window.location.href = 'your_url';