我正在使用FOSRestBundle開發REST API。我無法從控制器發送JSON響應。當我嘗試從該操作返回JSON響應時,我正將FooControllerFoo的fooAction的請求轉發給某個BarController,我得到的是空數組。symfony2無法在控制器中接收json響應
這裏的情景:
FooController.php
class FooController extends FOSRestController {
...
public function fooAction() {
...
$response = $this->forward('ApplicationPApiBundle:bar:getByZipCode', array(), array('zipcode' => $zipcode));
print_r($response); //getting blank array here
...
}
}
BarController.php
class BarController extends FOSRestController {
...
public function getByZipCodeAction() {
...
$response = new Response((array("one"=>"1", "two"=> "2")));
$response->headers->set('Content-Type', 'application/json');
// print_r($response); // after printing I can see data in json format
return $response;
}
}
,當我在FooController的的fooAction打印迴應,我認爲這是一個空數組但是當我在r之前在Barcontroller的getByZipCodeAction中打印它時剔除它,我看到與JSON內容適當的響應對象。
有人能幫我弄清楚這裏發生了什麼嗎?
編輯:返回之前在Barcontroller印刷 響應對象:
Symfony\Component\HttpFoundation\Response Object
(
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
(
[computedCacheControl:protected] => Array
(
[no-cache] => 1
)
[cookies:protected] => Array
(
)
[headerNames:protected] => Array
(
[cache-control] => Cache-Control
[date] => Date
[content-type] => Content-Type
)
[headers:protected] => Array
(
[cache-control] => Array
(
[0] => no-cache
)
[date] => Array
(
[0] => Wed, 24 Sep 2014 13:48:49 GMT
)
[content-type] => Array
(
[0] => application/json
)
)
[cacheControl:protected] => Array
(
)
)
[content:protected] => {"one":"1","two":"2"}
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] =>
)
=========================== ============================================================
Foocontroller打印後的響應對象來自轉發操作的響應:
Symfony\Component\HttpFoundation\Response Object
(
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
(
[computedCacheControl:protected] => Array
(
[no-cache] => 1
)
[cookies:protected] => Array
(
)
[headerNames:protected] => Array
(
[cache-control] => Cache-Control
[date] => Date
[content-type] => Content-Type
[x-debug-token] => X-Debug-Token
[x-debug-token-link] => X-Debug-Token-Link
)
[headers:protected] => Array
(
[cache-control] => Array
(
[0] => no-cache
)
[date] => Array
(
[0] => Wed, 24 Sep 2014 13:48:49 GMT
)
[content-type] => Array
(
[0] => application/json
)
[x-debug-token] => Array
(
[0] => 168be3
)
[x-debug-token-link] => Array
(
[0] => /app_dev.php/_profiler/168be3
)
)
[cacheControl:protected] => Array
(
)
)
[content:protected] => []
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] =>
)
請注意內容是空的。
您是否嘗試使用'JsonResponse'對象而不是'Response'? – 2014-09-24 14:47:25
@YannEugoné是的嘗試JsonResponse得到同樣的空白迴應 – Rahul 2014-09-24 14:52:55
是否由於我使用向前的子請求? – Rahul 2014-09-24 14:57:26