Dispatcher::asJSON PHP Method

asJSON() public method

Automatically updates the security token and proxy pending redirects.
Deprecation: the use of getAPIResponse() is encouraged
public asJSON ( array $data = [] ) : SS_HTTPResponse
$data array Data to be passed to the frontend.
return SS_HTTPResponse
    public function asJSON($data = [])
    {
        $securityToken = $this->getSecurityToken();
        $securityToken->reset();
        $data['NewSecurityID'] = $securityToken->getValue();
        $response = $this->getResponse();
        // If we received an AJAX request, we can't redirect in an ordinary way: the browser will
        // interpret the 302 responses internally and the response will never reach JS.
        //
        // To get around that, upon spotting an active redirect, we change the response code to 200,
        // and move the redirect into the "RedirectTo" field in the JSON response. Frontend can
        // then interpret this and trigger a redirect.
        if ($this->redirectedTo()) {
            $data['RedirectTo'] = $this->response->getHeader('Location');
            // Pop off the header - we are no longer redirecting via the usual mechanism.
            $this->response->removeHeader('Location');
        }
        $response->addHeader('Content-Type', 'application/json');
        $response->setBody(json_encode($data));
        $response->setStatusCode(200);
        return $response;
    }