Skip to content

Commit

Permalink
add JSONP support to JsonResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
havvg committed Mar 19, 2012
1 parent 05c523a commit 6788224
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/Symfony/Component/HttpFoundation/JsonResponse.php
Expand Up @@ -24,26 +24,37 @@ class JsonResponse extends Response
* @param mixed $data The response data
* @param integer $status The response status code
* @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
if (is_array($data) && 0 === count($data)) {
$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(
json_encode($data),
$content,
$status,
array_merge(array('Content-Type' => 'application/json'), $headers)
array_merge(array('Content-Type' => $contentType), $headers)
);
}

/**
* {@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 = '');
}
}
Expand Up @@ -86,4 +86,12 @@ public function testCreate()
$this->assertEquals('{"foo":"bar"}', $response->getContent());
$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'));
}
}

0 comments on commit 6788224

Please sign in to comment.