Joomla setRedirect doesn't work

2019-04-02 01:47发布

问题:

I have a simple Joomla controller, but I can't redirect anything.

According to the documentation:

class MyController extends MyBaseController {

 function import() {
    $link = JRoute::_('index.php?option=com_foo&ctrl=bar');
    $this->setRedirect($link);
  }

}
//The url contains & html escaped character instead of "&"

This should work, but I get a malformed URL. Is there something I'm missing here? Why is Joomla converting all the "&" characters into &'s? How am I suppose to use setRedirect?

Thank you

回答1:

Alright, I fixed it. So if anyone needs it:

instead of

$link = JRoute::_('index.php?option=com_foo&ctrl=bar');
$this->setRedirect($link);

use

$link = JRoute::_('index.php?option=com_foo&ctrl=bar',false);
$this->setRedirect($link);

to make it work.



回答2:

Glad you found your answer, and by the way, the boolean parameter in JRoute::_() is by default true, and useful for xml compliance. What it does is that inside the static method, it uses the htmlspecialchars php function like this: $url = htmlspecialchars($url) to replace the & for xml.



回答3:

Try this.

$mainframe = &JFactory::getApplication();
$mainframe->redirect(JURI::root()."index.php?option=com_foo&ctrl=bar","your custom message[optional]","message type[optional- warning,error,information etc]");


回答4:

After inspecting the Joomla source you can quickly see why this is happening:

if (headers_sent())
    {
        echo "<script>document.location.href='" . htmlspecialchars($url) . "';</script>\n";
    }
    else
    {
    ... ... ...

The problem is that your page has probably already output some data (via echo or some other means). In this situation, Joomla is programmed to use a simple javascript redirect. However, in this javascript redirect it has htmlspecialchars() applied to the URL.

A simple solution is to just not use Joomlas function and directly write the javascript in a way that makes more sense:

echo "<script>document.location.href='" . $url . "';</script>\n";

This works for me :)



回答5:

/libraries/joomla/application/application.php

Find line 400

    // If the headers have been sent, then we cannot send an additional location header
    // so we will output a javascript redirect statement.
    if (headers_sent())
    {
        echo "<script>document.location.href='" . htmlspecialchars($url) . "';</script>\n";
    }

replace to

    // If the headers have been sent, then we cannot send an additional location header
    // so we will output a javascript redirect statement.
    if (headers_sent())
    {
        echo "<script>document.location.href='" . $url . "';</script>\n";
    }

This works!