2017-12-09 19 views
-1

ajax呼び出しからHTMLテンプレート(SEOフレンドリー)を正しく返す方法が不思議でした。symfonyでajaxリクエストからhtmlテンプレートを正しく返す方法

$("div#target").click(function(event) { 
    $.ajax({ 
     type: "POST", 
     success: function(response) { 
      if(response.code === 202 && response.success) { 
       $("div#box").append(response.simpleData);  
      } 
     } 
    }); 
}); 

public function ajaxCallAction() { 
//..... 
    $response = array(
     "code"  => 202, 
     "success" => true, 
     "simpleData" => $simpleData 
    ); 

    return new JsonResponse($response); 
} 

とJSで私のような何かを:

単純なテンプレートの場合:私のアプリで

、私はレスポンスを返すように2つの貴様の方法を使用します

複合体テンプレート(より多くのt漢20行とさまざまなVAR):

public function ajaxCallAction() { 
    //... 
    $listOfObjects = $repo->findAll(); 
    $viewsDatas = [ 
     'listOfObjects' => $listOfObjects, 
     //....other vars 
    ]; 

    return $this->render('myAppBundle:template:complexTemplate.html.twig', $viewsDatas); 

    //in complexTemplate.html.twig, I loop on listOfObjects for example... 
} 

とコールのこの種のために、JSは、次のようになります。すべてのこれらのメソッドが作業しているが、2番目のものと、私たちは持っていけない

$("div#target").click(function(event) { 
    $.ajax({ 
     type: "POST", 
     success: function(response) { 
      $("div#box").append(response);  
     } 
    }); 
}); 

ステータスコード(それは重要ですか?)と私は直接formated HTMLテンプレートを返すことが重いことがわかります(例えば、このトピックWhy is it a bad practice to return generated HTML instead of JSON? Or is it?によると)。

あなたは、どのようにアヤックスコールをやっていますか?ここでベストプラクティスは何ですか?私のアプリで

答えて

0

、私は一般的にそのようなものを使用します。

$response = array( 
"code" => 200, 
"response" => $this->render('yourTemplate.html.twig')->getContent()); 

・ホープこのヘルプを!

編集

あなたの応答を返すにドキュメントで説明したように、あなたはJsonResponseを使用する必要があります。私は、ドキュメントのために見てきたが、理解していませんでし

return new JsonResponse($response); 
+0

http://symfony.com/doc/current/components/http_foundation.html#creating-a-json-response

は単にその使用"getContent()"は何ですか? http://api.symfony.com/4.0/Symfony/Component/HttpFoundation/Request.html#method_getContent – skytorner

+0

$ this-> render( 'template.html.twig')、symfonyはResponseオブジェクトを返します。このResponseで生成されたHTMLだけが必要なので、getContent()を使用してHTML文字列を取得し、それを前面に渡すことができます。 –

+0

私は本当にもっと感謝しなければならない!私はそれを試してみよう! – skytorner