I have a simple post which looks like
$.ajax({
url: '/album/createAlbum.html',
type: 'POST',
dataType: 'json',
async: true,
data: postData,
success: function (data) {
console.log("Successfully saved album");
console.log(data);
return data;
},
error: function (data) {
console.log("FAILED to save album");
return false;
}
});
and a simple action which looks like
public function createAlbumAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$album = $request->getPost('album');
//First check to see if the user already has that album
$albumObject = $this->_dataService->getAlbum($userID, $album);
if ($albumObject){
//This is the issue
$this->redirect()->toRoute('albumModule', array('controller' => 'album', 'action' => 'edit'));
} else {
$albumObject = $this->_dataService->createAlbum($userID, $album);
}
$messages = array();
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
} else {
$response->setContent(\Zend\Json\Json::encode(array('albumID' => $albumObject->getAlbumID())));
}
return $response;
}
The issue I'm having is on the redirect()
, I know that the redirect will send me to that route, but I need to tell the browser to GET
that route. I can't figure out how to do this from a POST
. I read something about setting the header to 303 so that the browser knows to do redirect, but I wouldn't know how to return that in my JSON response.
Even when I try to do header:("Location: " ...)
that won't tell the browser to GET the url.
I just ended up going with this
On the ajax call
error: function (request, textStatus, errorThrown) {
console.log("FAILED to save album");
//The Album already exists, so redirect to it
window.location = request.getResponseHeader('redirectURL');
return false;
},
On the ZF2 Action
$response->setStatusCode(Response::STATUS_CODE_301)->getHeaders()
->addHeaders(array('redirectURL' => $this->url()->fromRoute('albumModule', array('controller' => 'album', 'action' => 'edit', 'id' => $albumObject->getAlbumID()))));
return $response;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.