2014-03-25 32 views
0

Symfony2新手問題。Symfony2 + JS時間軸。如何將json文件傳遞給視圖?

我希望將Simile的時間線http://www.simile-widgets.org/timeline/用於我的Symfony2 web應用程序。 要做到這一點,我需要輸出以.json文件,並把它我timeline.html.twig視圖中傳遞給JS代碼:

... 
tl.loadJSON("http://localhost:{{ <my json file> }}?"+ (new Date().getTime()), function(json, url) {...} 

我能夠輸出使用JSON一個以.json文件。 html.twig模板+一jsonAction控制器

/** 
* Lists all Post entities. 
* 
* @Route("/json", name="Mario_Post_json") 
* @Method("GET") 
* @Template() 
*/ 
    public function jsonAction() 
{ 
$response = new Response(); 
$em = $this->getDoctrine()->getEntityManager(); 
$query = $this->getDoctrine() 
     ->getRepository('MarioBlogBundle:Post') 
     ->createQueryBuilder('e') 
     ->getQuery(); 

$results = $query->getArrayResult();  

$response->setContent(json_encode($results)); 
$response->headers->set('Content-Type', 'application/json'); 
    return $response; 
} 

我能夠通過加載和渲染一個靜態文件上傳.json:

tl.loadJSON("http://localhost{{ asset('bundles/marioblog/js/timeline/timeline.json') }}?"+ (new Date().getTime()), function(json, url) {...} 

但如果我嘗試的類似

變種
tl.loadJSON("http://localhost/symfony/web/app_dev.php/Mario/Post/jsonout?"+ (new Date().getTime()), function(json, url) {...} 

它總是失敗。 歡迎光臨幫助。

+0

我認爲JSON是在你模板渲染後(小枝作業後)提取的。因此,您需要在JavaScript級別執行JSON抓取(例如,通過發送執行PHP控制器的AJAX請求).PS:它是一個新手註釋。 –

+0

我的理解是,tl.loadJSON是在JS級別,不是嗎? – mario

+0

你能告訴我們:你的JS代碼如何執行你的PHP控制器?我不幸仍然無法在你的代碼中看到它。 –

回答

0

我覺得這種方法是這樣的:

function ajaxCall() 
{ 

    $.ajax({ 
        type: "GET", 
        url: // URL for the PHP controller, 
        dataType: 'json', 
        success: function(data){ 

       // give the data (a JSON in your case) to the Simile's js function 
      } 
        }); 

} 

注:這是AJAX使用jQuery。您可以使用任何其他的JavaScript庫,甚至可以使用原始的JavaScript來執行AJAX。

祝你好運

+0

我不確定。我會做一些功課,然後回來。無論如何。 – mario

相關問題