就像在Ruby on Rails上一样,你可以返回带有一些预渲染的Javascript来通过AJAX动态更新客户端站点.
在Symfony2中调用某些路由时如何返回Javascript?
例如,在updateItemAppearanceAction通过时\item\{itemId}\update_appearance,返回Javascript文件updateItemAppearance.js.twig,用array("item"->$item)?
非常感谢你!
在名为updateItemAppearanceAction的action方法中:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
// example controller.
class DefaultController extends Controller
{
/**
* @Route("/updateItemAppearance.js", name="default_update_item_appearance_js")
*/
public function updateItemAppearanceAction()
{
$optionalParams = array('some'=>'param');
$renderedView = $this->renderView('AppBundle:Default:updateItemAppearance.js.twig'); // 1.
$response = new Response($renderedView, $optionalParams)); // 2.
$response->headers->set('Content-Type','text/javascript'); // 3.
return $response;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您在updateItemAppearance.js.twig文件中编写的javascript可以通过常用方式嵌入为javascript文件.
<script src="/updateItemAppearance.js"></script>
Run Code Online (Sandbox Code Playgroud)
或者使用树枝路径助手.
<script src="{{ path('default_update_item_appearance_js') }}"></script>
Run Code Online (Sandbox Code Playgroud)