Source Viewer : /ajax/ajax-redirect.htm
$redirectLink
<div id="result" class="infoMsg">
#set ($flash = "")
#set ($flash = $session.flash)
#if ($flash != "")
$flash
#end
</div>
Clicking the link above will send an Ajax request to the server which returns
a url to redirect to. The url is returned from the server in a custom response
header called <tt>'REDIRECT_URL'</tt>.
<p/>
Since Ajax does not support redirects, JavaScript is used to simulate a redirect
by setting the value of <tt>window.location</tt> to the redirect url.
<script type="text/javascript" src="$context/assets/js/jquery-1.4.2.js"></script>
<script type="text/javascript">
// This example uses jQuery for making Ajax requests:
// http://api.jquery.com/jQuery.get/
// http://api.jquery.com/jQuery.ajax/
// Register a function that is invoked as soon as the DOM is loaded
jQuery(document).ready(function() {
var resultElm = jQuery("#result")
// Hide the result div initially if it contains no content
if (jQuery.trim(resultElm.text()).length == 0) {
resultElm.css("display", "none");
} else {
resultElm.css("display", "block");
}
// Register a 'click' handler that makes an Ajax request
jQuery("#redirectLinkId").click(function(event){
// Make ajax request
redirectLinkClicked();
// Prevent the default browser behavior of navigating to the link
return false;
})
})
function redirectLinkClicked() {
var link = jQuery('#redirectLinkId');
var extraData = link.attr('id') + '=1';
var url = link.attr('href');
jQuery.get(url, extraData, function(data, textStatus, xhr) {
// Retrieve the url to redirect from the Ajax response header
var redirect_url = xhr.getResponseHeader('REDIRECT_URL');
// Perform the redirect
window.location = redirect_url;
});
}
</script>