No, you cannot set headers in the same way as you do in RedirectResponse() when using RedirectCommand in an AJAX callback. The reason is that RedirectCommand uses JavaScript to redirect the user to the specified URL, and JavaScript does not have the ability to set headers.
If you need to pass headers to the redirected URL, you will need to do so on the server-side. One way to achieve this is to create a custom controller that handles the redirect, and then use RedirectResponse() with the headers you need. Here's an example:
Create a custom controller that handles the redirect and passes the necessary headers:
use Symfony\Component\HttpFoundation\RedirectResponse;
class MyController {
public function redirectWithHeaders() {
$url = 'http://www.example.com';
$headers = [
'custom' => 123,
];
return new RedirectResponse($url, 302, $headers);
}
}
In your AJAX callback, use Url::fromRoute() to generate the URL for your custom controller, and then use RedirectCommand to redirect the user to that URL:
use Drupal\Core\Url;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;
function ajaxCallback() {
$response = new AjaxResponse();
$url = Url::fromRoute('my_module.redirect_with_headers');
$response->addCommand(new RedirectCommand($url->toString()));
return $response;
}
Note that you will need to define a route for your custom controller in a my_module.routing.yml file. Here's an example:
my_module.redirect_with_headers:
path: '/redirect-with-headers'
defaults:
_controller: '\Drupal\my_module\Controller\MyController::redirectWithHeaders'
requirements:
_permission: 'access content'