add JSONP support to JsonResponse
This commit is contained in:
parent
05c523a7de
commit
678822459b
@ -24,26 +24,37 @@ class JsonResponse extends Response
|
|||||||
* @param mixed $data The response data
|
* @param mixed $data The response data
|
||||||
* @param integer $status The response status code
|
* @param integer $status The response status code
|
||||||
* @param array $headers An array of response headers
|
* @param array $headers An array of response headers
|
||||||
|
* @param string $jsonp A JSONP callback name
|
||||||
*/
|
*/
|
||||||
public function __construct($data = array(), $status = 200, $headers = array())
|
public function __construct($data = array(), $status = 200, $headers = array(), $jsonp = '')
|
||||||
{
|
{
|
||||||
// root should be JSON object, not array
|
// root should be JSON object, not array
|
||||||
if (is_array($data) && 0 === count($data)) {
|
if (is_array($data) && 0 === count($data)) {
|
||||||
$data = new \ArrayObject();
|
$data = new \ArrayObject();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$content = json_encode($data);
|
||||||
|
$contentType = 'application/json';
|
||||||
|
if (!empty($jsonp)) {
|
||||||
|
$content = sprintf('%s(%s);', $jsonp, $content);
|
||||||
|
// Not using application/javascript for compatibility reasons with older browsers.
|
||||||
|
$contentType = 'text/javascript';
|
||||||
|
}
|
||||||
|
|
||||||
parent::__construct(
|
parent::__construct(
|
||||||
json_encode($data),
|
$content,
|
||||||
$status,
|
$status,
|
||||||
array_merge(array('Content-Type' => 'application/json'), $headers)
|
array_merge(array('Content-Type' => $contentType), $headers)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@inheritDoc}
|
* {@inheritDoc}
|
||||||
|
*
|
||||||
|
* @param string $jsonp A JSONP callback name.
|
||||||
*/
|
*/
|
||||||
static public function create($data = array(), $status = 200, $headers = array())
|
static public function create($data = array(), $status = 200, $headers = array(), $jsonp = '')
|
||||||
{
|
{
|
||||||
return new static($data, $status, $headers);
|
return new static($data, $status, $headers, $jsonp = '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -86,4 +86,12 @@ class JsonResponseTest extends \PHPUnit_Framework_TestCase
|
|||||||
$this->assertEquals('{"foo":"bar"}', $response->getContent());
|
$this->assertEquals('{"foo":"bar"}', $response->getContent());
|
||||||
$this->assertEquals(204, $response->getStatusCode());
|
$this->assertEquals(204, $response->getStatusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testJsonp()
|
||||||
|
{
|
||||||
|
$response = new JsonResponse(array('foo' => 'bar'), 200, array(), 'callback');
|
||||||
|
|
||||||
|
$this->assertEquals('callback({"foo":"bar"});', $response->getContent());
|
||||||
|
$this->assertEquals('text/javascript', $response->headers->get('Content-Type'));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user