For example I have an action in Controller.
public function redirectnowAction() {
$this->_redirect( '/module/controller/action' );
}
When I call above action in n开发者_StackOverflowormal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.
JS code for AJAX
jQuery('.AjaxLink').live( 'click', function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html( snippets[id] );
}
});
});
How to redirect to action after AJAX request ?
Thanks
When you use a redirect, you send a header to the user's browser to fetch content at the new location.
AJAX requests are not usually setup to handle such redirects. They simply initiate a request, and return the response.
The best-case solution is to reorganize your code so a redirect is not necessary. If you cannot eliminate the redirect, you must update your Javascript to recognize the redirect status (HTTP 301, for example) and initiate a new request.
You cannot do it directly, here's what I'd do. In the action called via AJAX, include something like this:
echo Zend_Json::encode(array('redirect' => '/module/controller/action'));
This way, your AJAX call will receive a JSON object as a response. In jQuery's $.ajax()
call, you can specify a success
event, e.g.:
'dataType': 'json', // expects to receive a JSON-formatted response
'success': function(data, textStatus, jqXHR) {
window.location.replace('http://www.example.com' + data.redirect);
}
The ajax request itself would be subject to the redirect, not the browser window. Hence you would see the redirected content as the data returned via ajax. One solution would be to do a javascript redirect once the ajax request has been successfully run.
精彩评论